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.
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.