errantlinguist errantlinguist - 8 days ago 5
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.
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?


For example, if I try to import a symbol directly using
importlib.import_module(symbol_name)
, I just get an
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")


Executing the code above prints the following stack trace:

Traceback (most recent call last):
File "/home/stackoverflow/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'

Answer

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