Python – How to Import * from Module Name from Variable

pythonpython-import

As discussed here, we can dynamically import a module using string variable.

import importlib
importlib.import_module('os.path')

My question is how to import * from string variable?

Some thing like this not working for now

importlib.import_module('os.path.*')

Best Answer

You can do the following trick:

>>> import importlib
>>> globals().update(importlib.import_module('math').__dict__) 
>>> sin
<built-in function sin>

Be warned that makes all names in the module available locally, so it is slightly different than * because it doesn't start with __all__ so for e.g. it will also override __name__, __package__, __loader__, __doc__.

Update:

Here is a more precise and safer version as @mata pointed out in comments:

module = importlib.import_module('math')

globals().update(
    {n: getattr(module, n) for n in module.__all__} if hasattr(module, '__all__') 
    else 
    {k: v for (k, v) in module.__dict__.items() if not k.startswith('_')
})

Special thanks to Nam G VU for helping to make the answer more complete.

Related Question