The documentation on Packages says this:
The __init__.py files are required to make Python treat directories containing the file as packages. This prevents directories with a common name, such as string, unintentionally hiding valid modules that occur later on the module search path.
The documentation on Module Search Path says this:
When a module named
spam
is imported, the interpreter first searches for a built-in module with that name.
To properly understand this, I tried a few experiments:
-
Create a local directory
string
in the current directoryc:\WORK\dragondive\heavens-arena\python\modules
(from where python is called). Then do:import string print(type(string)) print(string.__file__)
Output:
<class 'module'> C:\Users\aravi\AppData\Local\Programs\Python\Python311\Lib\string.py
-
In the above local directory, create an empty
__init__.py
. Run the same code again:Output
<class 'module'> c:\WORK\dragondive\heavens-arena\python\modules\string\__init__.py
My sys.path
looks like this:
PS C:\WORK\dragondive\heavens-arena\python\modules> python main.py
[âC:\WORK\dragondive\heavens-arena\python\modulesâ, âC:\WORK\pythonâ, âC:\Users\aravi\AppData\Local\Programs\Python\Python311\python311.zipâ, âC:\Users\aravi\AppData\Local\Programs\Python\Python311\Libâ, âC:\Users\aravi\AppData\Local\Programs\Python\Python311\DLLsâ, âC:\Users\aravi\AppData\Local\Programs\Python\Python311â, âC:\Users\aravi\AppData\Local\Programs\Python\Python311\Lib\site-packagesâ]
Questions
How exactly does the presence of an __init__.py
cause the Python interpreter to âpreferâ the local string
over the built-in string?
The module search path documentation says built-in modules are searched first, but the packages documentation says __init__.py
prevents hiding valid modules that occur later on the module search path.
Does this imply that regular packages are loaded before modules?
This Stack Overflow answer (from 2011) suggests so, but thereâs also some disagreement in the comments.
Is the expected behaviour documented somewhere explicitly?