[New-bugs-announce] [issue43835] Dataclasses don't call base class __init__

Paul Pinterits report at bugs.python.org
Tue Apr 13 18:21:40 EDT 2021


New submission from Paul Pinterits <rawing7 at gmail.com>:

It's documented behavior that @dataclass won't generate an __init__ method if the class already defines one. It's also documented that a dataclass may inherit from another dataclass.

But what happens if you inherit from a dataclass that implements a custom __init__? Well, that custom __init__ is never called:

```
import dataclasses

@dataclasses.dataclass
class Foo:
    foo: int
    
    def __init__(self, *args, **kwargs):
        print('Foo.__init__')  # This is never printed

@dataclasses.dataclass
class Bar(Foo):
    bar: int

obj = Bar(1, 2)
print(vars(obj))  # {'foo': 1, 'bar': 2}
```

So if a dataclass uses a custom __init__, all its child classes must also use a custom __init__. This is 1) incredibly inconvenient, and 2) bad OOP. A child class should (almost) always chain-call its base class's __init__.

----------
components: Library (Lib)
messages: 391006
nosy: Paul Pinterits
priority: normal
severity: normal
status: open
title: Dataclasses don't call base class __init__
versions: Python 3.10, Python 3.7, Python 3.8, Python 3.9

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue43835>
_______________________________________


More information about the New-bugs-announce mailing list