8

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 something like this:

importlib.import_module('path.to.module', '*')

My reasons for not name-spacing the imported attributes are deliberate.

xgord
  • 4,606
  • 6
  • 30
  • 51
Michael
  • 2,031
  • 6
  • 21
  • 27

2 Answers2

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)
Hai Vu
  • 37,849
  • 11
  • 66
  • 93
6

Here is shorten version for @HaiVu answer which refers to this solution from @Bakuriu

import importlib

# import the module
mod = importlib.import_module('collections')

# make the variable global
globals().update(mod.__dict__)

Note:

  • This will import lots of things beside the user-defined variables

  • @HaiVu solution did the best of it ie. only import user-defined variables

Nam G VU
  • 33,193
  • 69
  • 233
  • 372