Import class from module depending on variable

Viewed 110

I have multiple classes in module and I want to import them depending on string variable.

class firstPRODUCT():
    pass
class secondPRODUCT():
    pass

In another module I have string variable which can be("first" or "second" or more), I want to import class string+"PRODUCT", (if string="first" import firstPRODUCT class, etc). Is there a way to do that in python? Tried with globals but it is syntax error.

string = "first"
from .work import(
    globals()[string+PRODUCT],
    my_func,
    my_other_func,
)
1 Answers

One solution is to import the module and use getattr to access the class you want by name.

from . import work

string = "first"
foo = getattr(work, f'{string}PRODUCT')
Related