The import statement loads a module or package and makes its contents available for use. Python provides several import forms: import module (the module name becomes a local name), from module import name (specific names are imported directly), from module import * (all public names are imported, generally discouraged), and import module as alias (the module is available under an alternative name).
When Python encounters an import statement, it searches for the module in the following order: sys.modules (the cache of already-imported modules), built-in modules, and then the directories listed in sys.path. The sys.path list typically includes the current directory, the site-packages directory (where pip installs packages), and directories specified by the PYTHONPATH environment variable.
Import mechanics are more complex than they appear. The import system uses finders and loaders (the importlib machinery) to locate and load modules. Circular imports — where module A imports module B which imports module A — are a common source of ImportError or AttributeError and can usually be resolved by restructuring code, using local imports (inside functions), or deferring imports. Understanding the import system deeply is valuable for building large Python applications.
Discussed in:
- Chapter 12: Modules and Packages — Import Variations