How to import * with __import__

2019-03-17 22:54发布

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

from module import *

标签: python import
3条回答
SAY GOODBYE
2楼-- · 2019-03-17 23:08

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

查看更多
Summer. ? 凉城
3楼-- · 2019-03-17 23:16

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(), ['*'])
查看更多
何必那么认真
4楼-- · 2019-03-17 23:16

The only way I found:

module = __import__(module, globals(), locals(), ['*'])
for k in dir(module):
    locals()[k] = getattr(module, k)
查看更多
登录 后发表回答