Lets assume I have a string for a class name (or part of a class name), and I have implementation somewhere. All I want, is to be able to get an instance of a class with the name in the variable.
For example,
dynamic_class_name = "Circle" # not a constant, comes from somewhere
corresponding_class = some_magic(dynamic_class_name)
corresponding_instance = corresponding_class()
I can think of several approaches from using __import__()
function, module attribute lookups, adding register
to classes, other ways of using namespaces, making auto-registering via metaclassing, all the way to using some heavy component architecture and interfaces...
The question is, what would be the simplest but elegant (understandable, intuitive, regular, not hackish) way to replace ugly code like?
if dynamic_class_name == "Circle":
inst = Circle()
elif dynamic_class_name == "Square":
inst = Square()
...
The bonus would be to have minimal impact on IDE's (like PyCharm) ability to infer types and instances.
Also a plus is that there is no need to have a special list with the classes in one place, so new classes can be drop in.
globals()[class_name]
will do the trick. The question is rather how to do it less hackish...Shape
: and use technique like in the following answer stackoverflow.com/questions/3862310/… and eg add a classmethod toShape
str_to_class
, what do you think?Plugin
orDriver
)?