__import__()
__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module
Import a module. Because this function is meant for use by the Python
interpreter and not for general use, it is better to use
importlib.import_module() to programmatically import a module.
The globals argument is only used to determine the context;
they are not modified. The locals argument is unused. The fromlist
should be a list of names to emulate ``from name import ...'', or an
empty list to emulate ``import name''.
When importing a module from a package, note that __import__('A.B', ...)
returns package A when fromlist is empty, but its submodule B when
fromlist is not empty. The level argument is used to determine whether to
perform absolute or relative imports: 0 is absolute, while a positive number
is the number of parent directories to search relative to the current module.
从文档中我们看到,返回值会因 fromlist 参数而不同:
m = __import__("a.b.c") <module "a" from ...> m = __import__("a.b.c", fromlist=["."]) <module "a.b.c" from ...>
importlib
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.mod
or..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
).
可以看到 import_module 和 __import__ 的最大区别是:
- import_module 返回的是指定的包/模块
- __import__ 返回的是最顶层的包/模块
Add Comment