问题
I have the following structure:
/blog
/app
/static
staticfile.py
/templates
templatefile.py
run.py
In run.py I have,
from app.static import staticfile
print("you run me")
In staticfile.py I have, print("ran from staticfile")
When I run python run.py I get,
ran from staticfile
you run me
I do not have __init__.py anywhere and I do not have a virtual environment. How does my reference work without the __init__.py file? Is it because I'm using Python 3.4? I am in Windows 7 if it matters.
EDIT: Best I can tell it is because I am in 3.4. I explicitly used C:\python27\python run.py and it failed until I put __init__.py.
回答1:
The 3.4 Glossary has this entry
namespace package
A PEP 420 package which serves only as a container for subpackages. Namespace packages may have no physical representation, and specifically are not like a regular package because they have no init.py file.
From my reading of the PEP, directories contained in directories on sys.path but not containing __init__.py are potential namespace directories. When run.py is run, '.', representing /blog, is added to the front of sys.path. Therefore, the directories in `/blog' are searched as potential namespace directories.
The PEP also says
If a developer knows that her package will never be a portion of a namespace package, then there is a performance advantage to it being a regular package (with an init.py ). Creation and loading of a regular package can take place immediately when it is located along the path. With namespace packages, all entries in the path must be scanned before the package is created.
In other words, every directory on sys.path is searched for possibly other modules in the app.static package, instead of stopping with '.' (/blog). I would go ahead and add the __init__.py files that you thought were required.
The PEP also noted the possible surprise effect.
Note that an ImportWarning will no longer be raised for a directory lacking an init.py file. Such a directory will now be imported as a namespace package, whereas in prior Python versions an ImportWarning would be raised.
回答2:
Yes, as of Python 3.3 you do not need to include __init__.py in your packages. Please see PEP 420 for more details.
来源:https://stackoverflow.com/questions/29216111/when-do-i-require-using-init-py