I'm currently trying my hands on the new dataclass constructions introduced in Python 3.7. I am currently stuck on trying to do some inheritance of a parent class. It looks like the order of the arguments are botched by my current approach such that the bool parameter in the child class is passed before the other parameters. This is causing a type error.
from dataclasses import dataclass
@dataclass
class Parent:
name: str
age: int
ugly: bool = False
def print_name(self):
print(self.name)
def print_age(self):
print(self.age)
def print_id(self):
print(f'The Name is {self.name} and {self.name} is {self.age} year old')
@dataclass
class Child(Parent):
school: str
ugly: bool = True
jack = Parent('jack snr', 32, ugly=True)
jack_son = Child('jack jnr', 12, school = 'havard', ugly=True)
jack.print_id()
jack_son.print_id()
When I run this code I get this TypeError:
TypeError: non-default argument 'school' follows default argument
How do I fix this?
You can use attributes with defaults in parent classes if you exclude them from the init function. If you need the possibility to override the default at init, extend the code with the answer of Praveen Kulkarni.
from dataclasses import dataclass, field
@dataclass
class Parent:
name: str
age: int
ugly: bool = field(default=False, init=False)
@dataclass
class Child(Parent):
school: str
jack = Parent('jack snr', 32)
jack_son = Child('jack jnr', 12, school = 'havard')
jack_son.ugly = True
Or even
@dataclass
class Child(Parent):
school: str
ugly = True
# This does not work
# ugly: bool = True
jack_son = Child('jack jnr', 12, school = 'havard')
assert jack_son.ugly
Note that with Python 3.10, it is now possible to do it natively with dataclasses.
Dataclasses 3.10 added the kw_only attribute (similar to attrs).
It allows you to specify which fields are keyword_only, thus will be set at the end of the init, not causing an inheritance problem.
Taking directly from Eric Smith blog post on the subject, they are two reasons people were asking for this feature:
What follow is the simplest way to do it with this new argument, but there are multiple ways you can use it to use inheritance with default values in the parent class:
from dataclasses import dataclass
@dataclass(kw_only=True)
class Parent:
name: str
age: int
ugly: bool = False
@dataclass(kw_only=True)
class Child(Parent):
school: str
ch = Child(name="Kevin", age=17, school="42")
print(ch.ugly)
Take a look at the blogpost linked above for a more thorough explanation of kw_only.
Cheers !
PS: As it is fairly new, note that your IDE might still raise a possible error, but it works at runtime