Whenever I do from 'x' import 'y'
I was wondering which one is considered the 'module' and which is the 'package', and why it isn't the other way around?
-
1Regarding why it's the not the other way around, see stackoverflow.com/questions/3600352/…– user7043Commented Oct 1, 2011 at 23:40
-
2I, for one, am thankful for this question, because the answer is concise and gives the exact needed knowledge. The documentation is all fine and dandy, but it's verbose and contains waaay more information than what the OP was asking for, and certainly more than I needed. I just wanted an answer to that specific question, and the answer below is exactly what I wanted. Many of us just don't need such formal or in-depth answers.– TeekinCommented Mar 24, 2018 at 15:47
-
A related concept to know - Classes vs. modules in Python– RBTCommented Jul 23, 2018 at 5:40
Add a comment
|
1 Answer
A Python module is simply a Python source file, which can expose classes, functions and global variables.
When imported from another Python source file, the file name is treated as a namespace.
A Python package is simply a directory of Python module(s).
For example, imagine the following directory tree in /usr/lib/python/site-packages
:
mypackage/__init__.py <-- this is what tells Python to treat this directory as a package
mypackage/mymodule.py
So then you would do:
import mypackage.mymodule
or
from mypackage.mymodule import myclass
-
Aha, so when you say that the file name is treated as a namespace, you would so something like this? "mymodule.var1" for the first case, or "myclass.var1" for the second? Commented Oct 2, 2011 at 4:08
-
1Not exactly. The package still counts as part of the namespace. If you want to do what you said then you need to do from mypackage import mymodule. Commented Oct 2, 2011 at 10:42
-
It might be useful to add something about namespace packages, for which the code need not necessarily all appear inthe same directory tree. Commented Apr 19, 2017 at 16:59
-
@holdenweb Never used the different mechanisms involved there directly, so not an expert. If you provide a detailed explanation about it in a new answer, I'll refer to it from mine. Commented Apr 22, 2017 at 4:18
-
Probably a bit too esoteric to be worth it, in retrospect Commented Apr 22, 2017 at 16:08