I am using Python dataclasses
module backported from Python 3.7.
I stumbled upon this behavior where a dataclass subclass does not inherit __repr__
:
from dataclasses import dataclass
@dataclass
class Person:
name: str
def __repr__(self):
return f'{self.__class__.__qualname__}({self.name})'
def print_something(self):
return self.name
@dataclass
class Employee(Person):
title: str
Here is the output
In [21]: e = Employee(name='Dmitry', title='Systems Engineer')
In [22]: p = Person(name='Dmitry')
In [23]: repr(e)
Out[23]: "Employee(name='Dmitry', title='Systems Engineer')"
In [24]: p = Person(name='Dmitry')
In [25]: repr(p)
Out[25]: 'Person(Dmitry)'
In [26]: p.print_something()
Out[26]: 'Dmitry'
In [27]: e = Employee(name='Dmitry', title='Systems Engineer')
In [28]: repr(e)
Out[28]: "Employee(name='Dmitry', title='Systems Engineer')"
In [29]: e.print_something()
Out[29]: 'Dmitry'
1) Why is this happening?
2) Is there a workaround for this behavior (except of redefining __repr__
in the subclass)?
This is happening because dataclass
automatically adds a __repr__
method, which just happens to be almost exactly the method you have in your base class, so you didn't notice. Pass repr=False
for dataclass
not to add a repr:
In [5]: from dataclasses import dataclass
...:
...: @dataclass(repr=False)
...: class Person:
...: name: str
...:
...: def __repr__(self):
...: return f'{self.__class__.__qualname__}({self.name})'
...:
...: def print_something(self):
...: return self.name
...:
...: @dataclass(repr=False)
...: class Employee(Person):
...: title: str
...:
In [6]: Person('foo')
Out[6]: Person(foo)
In [7]: Employee('foo', 'bar')
Out[7]: Employee(foo)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With