5. The import system:Python 官方文档
目录如下
- The import system
5.1. importlib
5.2. Packages
You can think of packages as the directories on a file system and modules as files within directories, but don’t take this analogy too literally since packages and modules need not originate from the file system. For the purposes of this documentation, we’ll use this convenient analogy of directories and files. Like file system directories, packages are organized hierarchically, and packages may themselves contain subpackages, as well as regular modules.
It’s important to keep in mind that all packages are modules, but not all modules are packages. Or put another way, packages are just a special kind of module. Specifically, any module that contains a path attribute is considered a package.
All modules have a name. Subpackage names are separated from their parent package name by a dot, akin to Python’s standard attribute access syntax. Thus you might have a package called email, which in turn has a subpackage called email.mime and a module within that subpackage called email.mime.text.
5.2.1. Regular packages
Python defines two types of packages, regular packages and namespace packages. Regular packages are traditional packages as they existed in Python 3.2 and earlier. A regular package is typically implemented as a directory containing an __init__
.py file. When a regular package is imported, this __init__
.py file is implicitly executed, and the objects it defines are bound to names in the package’s namespace. The __init__
.py file can contain the same Python code that any other module can contain, and Python will add some additional attributes to the module when it is imported.
For example, the following file system layout defines a top level parent package with three subpackages:
parent/
__init__.py
one/
__init__.py
two/
__init__.py
three/
__init__.py
Importing parent.one will implicitly execute parent/init.py and parent/one/init.py. Subsequent imports of parent.two or parent.three will execute parent/two/init.py and parent/three/init.py respectively.
5.2.2. Namesp
5.2.2. Namespace packages
5.3. Searching
5.3.1. The module cache
5.3.2. Finders and loaders
5.3.3. Import hooks
5.3.4. The meta path
5.4. Loading
5.4.1. Loaders
5.4.2. Submodules
5.4.3. Module spec
5.4.4. Import-related module attributes
5.4.5. module.path
5.4.6. Module reprs
5.4.7. Cached bytecode invalidation
5.5. The Path Based Finder
5.5.1. Path entry finders
5.5.2. Path entry finder protocol
5.6. Replacing the standard import system
5.7. Package Relative Imports
5.8. Special considerations for main
5.8.1. main.spec
5.9. References