Hello everybody,
I am having some trouble related to a a class hierarchy in Python.
In this hierarchy, each class holds a dictionary with config parameters.
My goal is to define a method get_config
such that an instance of any of these classes returns a merged dictionary containing the config parameters of the calling instance plus all the parameters defined in the super classes.
I hope the following code makes my problem clear:
class A:
_config = dict(a=1, b=2, c=3)
def get_config(self):
"""TODO"""
class B(A):
_config = dict(a=3, d=7)
a = A()
b = B()
assert a.get_config() == dict(a=1, b=2, c=3)
assert b.get_config() == dict(a=3, b=2, c=3, d=7)
I currently have the following solution:
def get_config(self, cls=None):
if cls is None:
cls = type(self)
print("self is of type", type(self).__name__)
print(f"{cls.__name__=}")
super_config = {}
next_super_cls = cls.mro()[1]
if next_super_cls is object:
return cls._config
super_config = self.get_config(cls=next_super_cls)
return {**super_config, **type(self)._config}
… but I wonder if there is a more straightforward way to do the same.
I am looking forward to your suggestions!