The Import System
What happens when you type import: how a name becomes a module object, where Python searches, and what it caches. It explains the daily errors — a script that imports from one directory but not another.
part ofPythonoverview, primer and where to startread it →on this pageshowhide
explore
- Modules and Regular Packages4 questions
- Absolute vs Relative Imports3 questions
- sys.path and sys.modules4 questions
- Circular Imports4 questions
- Script vs Module Execution4 questions
- Implicit Namespace Packages4 questions
- Module-Level __getattr__3 questions
- Importing by String Name4 questions
- Meta Path Finders4 questions
questions
page 2 of 2What do __name__, __file__ and __path__ hold on an imported Python package?
basics
~20 sname is the module's full dotted import name; file is the file it was loaded from, which for a regular package is its init.py rather than the directory; path is the submodule search list only packages have.
How does Python import modules straight out of a .zip file on sys.path?
basics
~20 sA .zip entry on sys.path is handled by sys.path_hooks: the zipimport hook accepts the entry and returns a zipimport.zipimporter for it, cached in sys.path_importer_cache. That finder reads .py and .pyc members out of the archive, so no file is ever unpacked to disk.
Why does a module-level `__getattr__` re-run its work on every attribute access?
basics
~20 sBecause the hook is consulted on every failed lookup and nothing caches what it returns. sys.modules stops an imported submodule executing twice, but the hook's body repeats until it binds the value into module globals.
How do you split one Python package namespace across two separately installed distributions?
basics
~10 sGive every distribution the same top-level directory with no init.py in it, let each own disjoint submodules, and declare those directories to the build backend so they ship. The import system merges the portions.
showing 31–34 of 34