aliases for imported modules with importlib

Viewed 448

Once you have imported foo module in which you have the bar class with

import importlib
foo = importlib.import_module('path/to/foo')

How do you do to simply call bar.run() instead of foo.bar.run()?

I guess you can to this bar = foo.bar but I want to do it for all objects in foo, and I can't do it each by each, it will take too much time.

1 Answers

You would likely need to enumerate the exported objects from the foo module, and assign them to global variables. In the normal mechanism for importing modules, * will either match the names listed in the __all__ variable or will grab all names that don't start with an underscore (_).

names = getattr(foo, '__all__', [])
if not names:
  names = [n for n in foo.__dict__.keys() if n[:1] != '_']

for name in names:
  globals()[name] = getattr(foo, name)
Related