python - import subpackage from a package not working?
I have the following files:
pack/__init__.py
pack/subpack/__init.__py
pack/subpack/mod2.py
And the following code fails on the last line:
from pack import * #should import everything
print subpack #NameError: name 'subpack' is not defined
I would expe开发者_Go百科ct the subpackage to be imported - why is there a difference, and how can I overcome it? Important: by "overcoming" I mean being able to refer to subpack
without needing to write pack.subpack
all the time.
You need to add
__all__ = ["mod1", "subpack"]
to pack/__init__.py
. Without this line, mod1
would not be imported either, so I wonder what is going on there. See also the relevant section in Guido's tutorial.
Try adding "import subpack" in pack/__init__.py
If you have __all__
declared, make sure 'subpack' appears there.
Alternative suggestion for Python 3 is:
# pack/__init__.py
from . import subpack
And, as already was mentioned, if __all__
is declared, then add 'subpack'
here.
And do not forget, that if you need NOT only:
print subpack
but also:
print subpack.mod2
then you need make similar operations in pack/subpack/__init.__py
file
精彩评论