文档 H2>
__import__的文档是内置函数中最差的。
__import__(...)
__import__(name, globals=None, locals=None, fromlist=(), level=0) -> 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. Level 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.如果仔细阅读,您会发现API最初旨在允许从模块中延迟加载函数。但是,这不是CPython的工作方式,而且我不知道Python的任何其他实现是否已成功实现。
相反,CPython在第一次导入时执行模块命名空间中的所有代码,之后模块缓存在sys.modules中。
__import__仍然有用。但是根据文档理解它的作用是相当困难的。
完全使用__import__ h2>
要调整完整功能以演示当前的__import__ API,这里是一个包装器函数,其中包含更清晰,更好的文档API。
def importer(name, root_package=False, relative_globals=None, level=0):
""" We only import modules, functions can be looked up on the module.
Usage:
from foo.bar import baz
>>> baz = importer('foo.bar.baz')
import foo.bar.baz
>>> foo = importer('foo.bar.baz', root_package=True)
>>> foo.bar.baz
from .. import baz (level = number of dots)
>>> baz = importer('baz', relative_globals=globals(), level=2)
"""
return __import__(name, locals=None, # locals has no use
globals=relative_globals,
fromlist=[] if root_package else [None],
level=level)为了证明,例如从姊妹套餐到巴兹:
baz = importer('foo.bar.baz')
foo = importer('foo.bar.baz', root_package=True)
baz2 = importer('bar.baz', relative_globals=globals(), level=2)
assert foo.bar.baz is baz is baz2
模块中名称的动态访问 h2>
要从baz模块按名称动态访问全局变量,请使用getattr。例如:
for name in dir(baz):
print(getattr(baz, name))