Specific example:
in /tmp/test
, I create a file itertools.py
with following content:
def f():
print("it is my own itertools.")
I know there is a builtin module named itertools
Then I run python3
from /tmp/test
,
>>> import itertools
>>> itertools.__dict__
{'_tee': <class 'itertools._tee'>, 'groupby': <class 'itertools.groupby'>, ...}
So I import the builtin module itertools
instead of /tmp/test/itertools.py
.
It seems that Python searches for a builtin module before searching for a nonbuiltin module. This is contrary to Python modules with identical names (i.e., reusing standard module names in packages). Why?
General rules:
From Python in a Nutshell
When a module is loaded,
__import__
first checks whether the module is built-in. The tuplesys.builtin_module_names
names all built-in modules, but rebinding that tuple does not affect module loading.
The search for built-in modules also looks for modules in platform-specific loca‐ tions, such as the Registry in Windows.If module M is not built-in,
__import__
looks for M ’s code as a file on the filesystem.__import__
looks at the strings, which are the items of listsys.path
, in order.
From Learning Python
In many cases, you can rely on the automatic nature of the module import search path and won’t need to configure this path at all. If you want to be able to import user- defined files across directory boundaries, though, you will need to know how the search path works in order to customize it. Roughly, Python’s module search path is composed of the concatenation of these major components, some of which are preset for you and some of which you can tailor to tell Python where to look:
- The home directory of the program
- PYTHONPATH directories (if set)
- Standard library directories
- The contents of any .pth files (if present)
- The site-packages home of third-party extensions
Are the five places in Learning Python stored in sys.path
?
Are the five places in Learning Python searched only after failing to find a builtin module in sys.builtin_module_names
?
Is "3. Standard library directories" not including the builtin modules? Where are the builtin modules stored? What are the relations between "3. Standard library directories" and the builtin modules?
Thanks.