globals() returns a dictionary containing all symbols defined in the global scope of the module (including classes A and B):
a_and_b_module.py
class A: pass
class B: pass
def get_cls(cls_name):
return globals()[cls_name]
If you are looking for simplicity
If the code that will call this function is inside the module, then you can eliminate the function altogether and use globals()[cls_name] directly.
If the code that will call this function is outside the module, then you could use getattr function:
a_and_b_module.py
class A: pass
class B: pass
another_file.py
import a_and_b_module
cls_name = 'A'
chosen_cls = getattr(a_and_b_module, cls_name)
If you are looking for complete control
The problem with the approach above is that it could return anything defined in a_and_b_module.py, not restricting itself to A and B. If you want to make sure only A and B can be returned:
class A: pass
class B: pass
allowed_classes = ('A', 'B')
def get_cls(cls_name):
assert cls_name in allowed_classes
return globals()[cls_name]
Note: you might also be interested in the concept of factory.
dictlikecls = {'classA': A, 'classB': B}, and then you can callcls.get('classA')for yourget_objimplementation. This is a start though, but without much more details on what you are actually wanting to do the actual answer can be quite different.