Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dataclass subclass does not inherit __repr__

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)?

like image 247
Dmitry Figol Avatar asked Oct 31 '18 19:10

Dmitry Figol


1 Answers

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)
like image 119
juanpa.arrivillaga Avatar answered Nov 01 '22 07:11

juanpa.arrivillaga