How to import * with __import__

前端 未结 3 1158
时光取名叫无心
时光取名叫无心 2021-02-07 07:36

What\'s the best approach to execute the following using __import__ so that I may dynamically specify the module?

from module import *
相关标签:
3条回答
  • 2021-02-07 07:51

    The only way I found:

    module = __import__(module, globals(), locals(), ['*'])
    for k in dir(module):
        locals()[k] = getattr(module, k)
    
    0 讨论(0)
  • 2021-02-07 07:59

    __import__() never adds anything to the local scope. You will have to go through the returned module, accessing its attributes as desired.

    0 讨论(0)
  • 2021-02-07 08:01

    It's the same as a normal from-import call, you just pass it a list containing '*' for the fromlist:

    moduleName = "foo"
    __import__(moduleName, globals(), locals(), ['*'])
    
    0 讨论(0)
提交回复
热议问题