from module import foo
is equivalent to foo = __import__('module').foo
. It does have to run the whole file to create the module object.
But importlib.import_module
is a bit easier to use (especially for submodules) so that would be
foo = import_module('module').foo
If the attribute access also needs to be dynamic, you can use getattr
, so
def from_module_get(module_name, attr):
return getattr(import_module(module_name), attr)
>>> from_module_get('math', 'tau')
6.283185307179586
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…