I want to create instances of several classes at runtime, based on configuration xml files which contain the specific class type and other stuff. Let's start with a simple example:
class ParentClass:
@staticmethod
def create_subclass(class_type: str, xml):
if class_type == 'childA':
return ChildClassA(xml)
elif class_type == 'childB':
return ChildClassB(xml)
else:
return ParentClass(xml)
def __init__(self, xml):
print('\nParent stuff done.')
class ChildClassA(ParentClass):
def __init__(self, xml):
super().__init__(xml)
print('Class A stuff done.')
class ChildClassB(ParentClass):
def __init__(self, xml):
super().__init__(xml)
print('Class B stuff done.')
ParentClass.create_subclass('childA', None)
ParentClass.create_subclass('childB', None)
ParentClass.create_subclass('unknown', None)
The output is as expected:
Parent stuff done.
Class A stuff done.
Parent stuff done.
Class B stuff done.
Parent stuff done.
As the hierarchy grows larger I want to have the parent class in a separate module and each child class in a separate module. Obviously, I need to import the parent module to the child class modules. Due to the create subclass
method, the parent class module needs to know about the child classes. Importing those to the parent module would cause a circular import which is considered bad design.
What would be a good solution to solve this issue? Are there better ways to create the subclass instances?