3

I have a list of module names in an array. I would like to import all these modules from an already imported class. It seems like I can't use from TestModule __import__(name)

How can I do that? Here is what I have:

import MainModule
arr = \
    ['Module1', 'Module2', 'Module3', 'Module4', 'Module5']
for string in arr:
     # Use FROM  to import the sub classes somehow
     from MainModule __import__(string)

Of course Python won't allow me to do that.

Shadow
  • 170
  • 1
  • 11

1 Answers1

1
import MainModule
arr = \
    ['Module1', 'Module2', 'Module3', 'Module4', 'Module5']
for string in arr:
    globals()[string] = getattr(MainModule, string)

might help you, although modifying globals() is not very elegant.

Better

modules = {string: getattr(MainModule, string) for string in arr}

and then do with modules whatever you want, e. g.

class MyModulesHolder(dict):
    pass

modules = MyModulesHolder()
modules.__dict__ = modules
modules.update({string: getattr(MainModule, string) for string in arr})

so that you can do modules.Module2.whatever().

glglgl
  • 89,107
  • 13
  • 149
  • 217