errantlinguist errantlinguist - 1 year ago 82
Python Question

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

In Python, it is possible to dynamically import an entire module using

, which returns the specified package or module (e.g.
). 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
of the module
is imported into the symbol table of the importing module?

For example, if I try to import a symbol directly using
, I just get an

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")

Executing the code above prints the following stack trace:

Traceback (most recent call last):
File "/home/stackoverflow/dev/", line 6, in <module>
symbol = importlib.import_module("basename", "os.path.basename")
File "/usr/lib/python3.5/importlib/", 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'

Answer Source

You have to look up the symbol you need in the module object that is returned by import_module using getattr:

imported_module = importlib.import_module("os.path")
imported_symbol = getattr(imported_module, "basename")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download