I wish to use dataclasses in Python to create a base class and several derived classes. These classes will contains complex attributes, such as dictionaries. I want the derived classes to change only part of the dictionary defined by the base class, is this possible? Or am I better off with plain old classes?
Shown in the code snippet is the current situation, this seems wasteful in terms of code duplication.
In this example I could define a function that accepts a single parameter instead of the lambdas, but in a real world example I would have to define a function for every such case and that would be cumbersome.
from dataclasses import dataclass, field
@dataclass
class BaseDataClass:
simple_field_one: int = 100
simple_field_two: int = 200
complex_field: dict = field(default_factory=lambda: {
'x': 0.1,
'y': ['a', 'b']
})
@dataclass
class DerivedDataClass(BaseDataClass):
simple_field_two: int = 300 # this is easy
complex_field: dict = field(default_factory=lambda: {
'x': 0.1,
'y': ['a', 'c']
}) # this is wasteful. All I changed was complex_field['y'][1]