pythoninheritancepython-dataclasses

Derived python dataclass cannot override default value?


In the following code snippet the dataclass Derived is derived from dataclass Base. The Derived dataclass is setting new default values for field1 and field2.

from dataclasses import dataclass

@dataclass
class Base:
    field1: str
    field2: str = "default_base_string"


@dataclass
class Derived(Base):
    field1 = "default_string1"
    field2 = "default_string2"

print(Derived())

Because Derived is a dataclass and has set a default value for all member variables field1 and field2, I expected that I could simply initialize the class calling Derived(). However I get the following error:

TypeError: Derived.__init__() missing 1 required positional argument: 'field1'

Is it not possible to set the default value for a member variable in a derived dataclass, so that this member variable becomes optional in the autogenerated __init__() method? Must I always define my own __init__() method in the Derived class? Or am I doing something wrong here?


Solution

  • To set default values in Derived you need to add the type annotation

    @dataclass
    class Derived(Base):
        field1: str = "default_string1"
        field2: str = "default_string2"
    
    
    print(Derived()) # Derived(field1='default_string1', field2='default_string2')