Python 的 "from <module> import <symbol>" 的动态等价物

Dynamic equivalent of Python's "from <module> import <symbol>"

在Python中,可以dynamically import an entire module using importlib.import_module(name), which returns the specified package or module (e.g. pkg.mod). However, is there no analogous way to dynamically import a specific function/class/etc. from a given module in the same fashion as done using e.g. from foo import bar, where the symbol bar of the module foo is imported into the symbol table of the importing module?

例如,如果我尝试直接使用 importlib.import_module(symbol_name) 导入符号,我只会得到一个 ImportError:

import importlib

# Importing an entire module works fine
imported_module = importlib.import_module("os.path")
# This doesn't work
imported_symbol = importlib.import_module("os.path.basename")

执行上面的代码打印以下堆栈跟踪:

Traceback (most recent call last):
  File "/home/Whosebug/dev/importtest.py", line 6, in <module>
    symbol = importlib.import_module("basename", "os.path.basename")
  File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked
ImportError: No module named 'basename'

您必须使用 getattr:

import_module 返回的模块对象中查找您需要的符号
imported_module = importlib.import_module("os.path")
imported_symbol = getattr(imported_module, "basename")

import_module 方法只接受模块。

您可以尝试以下操作来访问模块的 method/attribute

imported_symbol = importlib.import_module("os.path").basename