Import * from module by importing via string

后端 未结 2 438
攒了一身酷
攒了一身酷 2021-01-14 07:14

I know I can use importlib to import modules via a string. How can I recreate the import * functionality using this library? Basically, I want some

2条回答
  •  梦毁少年i
    2021-01-14 08:10

    Here is a solution: import the module, then one by one make alias in the current namespace:

    import importlib
    
    # Import the module
    mod = importlib.import_module('collections')
    
    # Determine a list of names to copy to the current name space
    names = getattr(mod, '__all__', [n for n in dir(mod) if not n.startswith('_')])
    
    # Copy those names into the current name space
    g = globals()
    for name in names:
        g[name] = getattr(mod, name)
    

提交回复
热议问题