python37: Does @dataset call super.__init__(...)?

Viewed 65

Suppose I have a complicated class with a lot of inputs. This class is not a dataclass class. Further, if I import it explicitly, I would like it to complain if I do not provide all of the arguments.

However, for interfacing purposes and clean code, I would like to define default values for the constructors and pass around arguments for the complex class as, more or less, a 'defined' dict.

This is a good task for the dataclass, and I have defined a dataclass class containing all the arguments with defaults, and which I modify and manipulate.

@dataclass
ComplicatedClassArgs:
   arg1: int
   arg2: bool = False
   ...

My question amounts to: can I write the following, and expect and/or tell the dataclass to call super.init(...) with all the named attributes I have defined?

@dataclass
ComplicatedClassArgs(ComplicatedClass):
    arg1: int
    arg2: bool = False

    def some_meta_arg_manipulation_function(...):
        pass

    def some_other_arg_related_function(...):
        pass

Such that I know I have composed a more advanced inner class behavior with a dataclass entry point?

1 Answers

I might have misunderstood your use case, but it looks to me like inheritance is the wrong tool for the job here. How about a simple @classmethod?

@dataclass
ComplicatedClassArgs:
    arg1: int
    arg2: bool

    @classmethod
    def from_dict(cls, kwargs=None):
        """"ComplicatedClassArgs factory.

        This method provides sensible default values that 
        may or may not be replaced through the input kwargs. 
        """
        if kwargs is None:
            kwargs = {}
        default_params = {
            'arg1': 1,
            'arg2': False
        }
        return cls(**{**default_params, **kwargs})

>>> ComplicatedClassArgs()
Traceback (most recent call last):
  ...
TypeError: __init__() missing .. required positional arguments
>>> ComplicatedClassArgs.from_dict()
ComplicatedClassArgs(arg1=1, arg2=False)
Related