Python dynamic import - how to import * from module name from variable?

前端 未结 1 885
天涯浪人
天涯浪人 2020-12-14 10:29

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

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

My quest

相关标签:
1条回答
  • 2020-12-14 10:47

    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.

    0 讨论(0)
提交回复
热议问题