0

I have a very large set of classes each with many parameters. I would like to set the class parameters based on a list of default parameter dictionaries for each class, whilst making each parameter initialisable in the __init__ declaration and directly as an instance attribute. I would like to put callbacks for some functions to trigger when some of these parameters are updated.

An example:

I've been setting them so far in a standard style of inheritance:

class Flour(object):
    def __init__(self, a=0, b=1, c=2, *args, **kwargs):
        super(Flour, self).__init__(*args, **kwargs)
        self.a = a
        self.b = b
        self.c = c

class Donut(Flour):
    def __init__(self, d=0, e=1, f=2, *args, **kwargs):
        super(Donut, self).__init__(*args, **kwargs)
        self.d = d
        self.e = e
        self.f = f
        

I would like to do something like this:

default_flour_parameters = {
    "a": 0,
    "b": 1,
    "c": 2
}


class Flour(object):
    def __init__(self,
                 **default_flour_parameters, # some sort of unpacking function like **kwargs but I also want to unpack inherited arguments, I do not want the dictionary to be an explicit argument
                 *args,
                 **kwargs):
        super(Car, self).__init__(*args, **kwargs)
        # Iterate here over the unpacked parameters within default_flour_parameters and setattr(self, key, value)

default_donut_parameters = {
    "d": 0,
    "e": 1,
    "f": 2
}


class Donut(Flour):
    def __init__(self,
                 **default_donut_parameters, # some sort of unpacking function like **kwargs but I also want to unpack inherited arguments, I do not want the dictionary to be an explicit argument
                 *args,
                 **kwargs):
        super(Donut, self).__init__(*args, **kwargs)
        # Iterate here over the unpacked parameters within default_donut_parameters and setattr(self, key, value)

So you cannot unpack two dictionaries in a class **kwargs and eg. **default_donut_parameters which is part of the issue. The idea is to be able to call Donut().a and get 0.

I'd also like to add a callback when any of these parameters are set, I assume just overwriting __setattr__ could do to trigger an observable callback.

Closest answers I have found are:

On the double dict unpacking structure for class inheritance I get:

    **kwargs):
    ^
SyntaxError: invalid syntax
  • Related https://stackoverflow.com/questions/74748675/python-update-cached-property-when-field-of-attribute-changes – dquintero May 15 '23 at 21:10

0 Answers0