What is the reason python needs
This question already has an answer here:
The documentation is very clear on this - your project structure could look like this:
app
- common
- init.py
- resources
- string
- src
If Python implicitly treated the directories as packages, the "string" directory could present a name clash with Python's built-in string module (https://docs.python.org/2/library/string.html). This means that when calling import string
, the module is ambiguous.
__init__.py
also adds a bit of functionality: code there is executed when initializing the package and can therefore be used to do package setup of some kind.
If you have a directory named string
that isn't a package, in a location where Python searches for modules and packages (such as the current working directory), Python shouldn't try to import that when you do import string
. The __init__.py
requirement lets Python know it should keep going rather than treating that directory as a package.
this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.
Suppose you have a directory where you do work for school, some of this involving python. You have a directory for math, which you have called math. You also have a python module you wrote, so the top level directory "school" has been added to the python path so you can use it anywhere
School/
math/
hw1.txt
integrate.py
MyPythonModule/
__init__.py
someClass.py
someFunc.py
When you are using python later and you are searching for MyPythonModule, python will open up School/
Then it sees math/
and MyPythonModule/
If you are using math in your python program, and there was not a way to distinguish between module ../lib/site-packages/math/
and non module ../School/math/
then python will treat your file ../School/math/
as the package math; breaking code without you knowing why.
上一篇: 我为什么需要
下一篇: python需要什么原因