-1

Looking to import a list of classes and then use them later in the script. Therefore, the from x import * logic does not work. Here is a more specific layout of what I am looking to do.

class_list = [x, y, z, zz, zzz]
from my_module import class_list

and then later on in the code still be able to call x.random_attribute. Not sure if this is possible!

To clarify I am trying to avoid the following:

from my_module import x, y, z, zz, zzz

as I have about 50 class objects I am importing and more will be added over time. Would love to have the list as a separate object.

Stephen Strosko
  • 597
  • 1
  • 5
  • 18
  • possible duplicate of https://stackoverflow.com/questions/39850390/syntax-of-importing-multiple-classes-from-a-module – AviatorX Apr 16 '19 at 15:28
  • If you are in control of `my_module`, you can add the classes to `my_module.__all__`; then `from my_module import *` will import just your desired classes. – chepner Apr 16 '19 at 15:38

1 Answers1

1
class_list = ['x', 'y', 'z', 'zz', 'zzz']
for c in class_list:
    exec('from my_module import ' + c)
joedeandev
  • 626
  • 1
  • 6
  • 15
  • Beware of insecurities that you run into due to usage of eval. Check this thread: https://stackoverflow.com/questions/661084/security-of-pythons-eval-on-untrusted-strings#:~:text=eval()%20will%20allow%20malicious,hard%20to%20do%20this%20properly. – Constantin Aug 31 '22 at 15:42