How come my python import doesn't work?
This works:
from story.apps.document import core
print core.submit()
This doesn't work:
from story import apps
print apps.document.core.submit()
"story" is a directory. Inside it, there is "apps" directory. Inside i开发者_如何学Ct, there is "document" directory. "core.py" is a file.
There is a __init__.py
in every directory.
The __init__.py
file tells python to interpret the directory as a package, but it does not necessarily tell python to import sub-packages or other files from the directory (although it may, if you add the appropriate import
statements).
With large package hierarchies, it is often preferable to require sub-packages to be imported explicitly.
When you do story.apps.document import core
, you're telling the Python interpreter to match a module of the description story.apps.document
, import it, then load the variable core
from its namespace into your current one.
Because core
is a file module it has in its namespace variables defined within that file e.g., submit
.
When you do from story import apps
, you're telling the Python interpreter to match a module of the description story
, import it, then load the variable apps
from its namespace into your current one.
Because apps
is a directory module it has within its namespace variables defined in its __init__.py
and other modules in that directory. So apps
knows about the document
but it doesn't know anything about document
's submodule core
.
FYI: The reason this sometimes confuses people is because of stuff like this...
Works just fine:
# File1
import story.apps.document
story.apps.document.core()
Doesn't work:
# File2
import story
story.apps.document.core() # <-- Looks like the same function call, but is an Error
For file1
, The import works because the the import
operation tries to intelligently find things on the filesystem. The function call works because the module document
was imported, and it is merely named story.apps.document
.
For file2
, the function call doesn't work because there's nothing intelligent about the dot operator, it merely attempts to access attributes on the Python object--it doesn't know anything about filesystems or modules.
when you do from story import apps, you don't include all the subpackages inside apps, for that, you do something like,
from story.apps.document import *
This only works if story/__init__.py
imports apps
.
IN the second example you are only importing the package. Python does not automatically import subpackages or modules. You have to explicitly do it, as in the first example. Do a dir(apps)
and you'll see it is just an empty package.
精彩评论