5

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.

2
  • Can't you do from foo import * here?
    – Raghul Raj
    Commented Jul 29, 2020 at 15:15
  • 2
    no , that's the point Commented Jul 30, 2020 at 7:33

1 Answer 1

2

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)
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.