skip to content

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 pageshow

questions

page 2 of 2

What do __name__, __file__ and __path__ hold on an imported Python package?

level: middleimportance: nice to knowfreq 20%

basics

~20 s

name 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.

open as a page

How does Python import modules straight out of a .zip file on sys.path?

level: seniorimportance: nice to knowfreq 14%

basics

~20 s

A .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.

open as a page

Why does a module-level `__getattr__` re-run its work on every attribute access?

level: seniorimportance: nice to knowfreq 15%

basics

~20 s

Because 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.

open as a page

How do you split one Python package namespace across two separately installed distributions?

level: seniorimportance: nice to knowfreq 18%

basics

~10 s

Give 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.

open as a page

showing 31–34 of 34