How does one do the equivalent of “import * from module” with Python's __import__ function?

前端 未结 5 780
温柔的废话
温柔的废话 2020-11-29 03:51

Given a string with a module name, how do you import everything in the module as if you had called:

from module import *

i.e. given string

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 04:38

    It appears that you can also use dict.update() on module's dictionaries in your case:

    config = [__import__(name) for name in names_list]
    
    options = {}
    for conf in config:
        options.update(conf.__dict__)
    

    Update: I think there's a short "functional" version of it:

    options = reduce(dict.update, map(__import__, names_list))
    

提交回复
热议问题