importlib --- import 的實作¶
在 3.1 版被加入.
簡介¶
importlib 的目的可分為三個部分。
第一是提供 Python 原始碼中 import 陳述式的實作(因此,也延伸到 __import__() 函式)。這讓 import 實作可以移植到任何 Python 直譯器。同時,這也提供了一個比用其他程式語言實作更容易理解的版本。
Two, the components to implement import are exposed in this
package, making it easier for users to create their own custom objects (known
generically as an importer) to participate in the import process.
Three, the package contains modules exposing additional functionality for managing aspects of Python packages:
importlib.metadatapresents access to metadata from third-party distributions.importlib.resourcesprovides routines for accessing non-code "resources" from Python packages.
也參考
- import 陳述式
The language reference for the
importstatement.- Packages specification
Original specification of packages. Some semantics have changed since the writing of this document (e.g. redirecting based on
Noneinsys.modules).__import__()函式The
importstatement is syntactic sugar for this function.- sys.path 模組搜尋路徑的初始化
The initialization of
sys.path.- PEP 235
Import on Case-Insensitive Platforms
- PEP 263
Defining Python Source Code Encodings
- PEP 302
New Import Hooks
- PEP 328
Imports: Multi-Line and Absolute/Relative
- PEP 366
Main module explicit relative imports
- PEP 420
Implicit namespace packages
- PEP 451
A ModuleSpec Type for the Import System
- PEP 488
Elimination of PYO files
- PEP 489
多階段擴充模組初始化
- PEP 552
Deterministic pycs
- PEP 3120
Using UTF-8 as the Default Source Encoding
- PEP 3147
PYC Repository Directories
函式¶
- importlib.__import__(name, globals=None, locals=None, fromlist=(), level=0)¶
An implementation of the built-in
__import__()function.備註
Programmatic importing of modules should use
import_module()instead of this function.
- importlib.import_module(name, package=None)¶
Import a module. The name argument specifies what module to import in absolute or relative terms (e.g. either
pkg.modor..mod). If the name is specified in relative terms, then the package argument must be set to the name of the package which is to act as the anchor for resolving the package name (e.g.import_module('..mod', 'pkg.subpkg')will importpkg.mod).The
import_module()function acts as a simplifying wrapper aroundimportlib.__import__(). This means all semantics of the function are derived fromimportlib.__import__(). The most important difference between these two functions is thatimport_module()returns the specified package or module (e.g.pkg.mod), while__import__()returns the top-level package or module (e.g.pkg).If you are dynamically importing a module that was created since the interpreter began execution (e.g., created a Python source file), you may need to call
invalidate_caches()in order for the new module to be noticed by the import system.在 3.3 版的變更: Parent packages are automatically imported.
- importlib.invalidate_caches()¶
Invalidate the internal caches of finders stored at
sys.meta_path. If a finder implementsinvalidate_caches()then it will be called to perform the invalidation. This function should be called if any modules are created/installed while your program is running to guarantee all finders will notice the new module's existence.在 3.3 版被加入.
在 3.10 版的變更: Namespace packages created/installed in a different
sys.pathlocation after the same namespace was already imported are noticed.
- importlib.reload(module)¶
Reload a previously imported module. The argument must be a module object, so it must have been successfully imported before. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter. The return value is the module object (which can be different if re-importing causes a different object to be placed in
sys.modules).When
reload()is executed:Python module's code is recompiled and the module-level code re-executed, defining a new set of objects which are bound to names in the module's dictionary by reusing the loader which originally loaded the module. The
initfunction of extension modules is not called a second time.As with all other objects in Python the old objects are only reclaimed after their reference counts drop to zero.
The names in the module namespace are updated to point to any new or changed objects.
Other references to the old objects (such as names external to the module) are not rebound to refer to the new objects and must be updated in each namespace where they occur if that is desired.
There are a number of other caveats:
When a module is reloaded, its dictionary (containing the module's global variables) is retained. Redefinitions of names will override the old definitions, so this is generally not a problem. If the new version of a module does not define a name that was defined by the old version, the old definition remains. This feature can be used to the module's advantage if it maintains a global table or cache of objects --- with a
trystatement it can test for the table's presence and skip its initialization if desired:try: cache except NameError: cache = {}
It is generally not very useful to reload built-in or dynamically loaded modules. Reloading
sys,__main__,builtinsand other key modules is not recommended. In many cases extension modules are not designed to be initialized more than once, and may fail in arbitrary ways when reloaded.If a module imports objects from another module using
from...