Paul Pinterits <[email protected]> added the comment:
Admittedly, with the way dataclasses accept their __init__ arguments, figuring
out which arguments to consume and which to pass on isn't a trivial task.
If a dataclass Bar inherits from a dataclass Foo, then Bar.__init__ is (for all
intents and purposes) defined as
def __init__(self, foo, bar):
Because the arguments for the parents *precede* the arguments for Bar, it's not
easy to create an equivalent __init__ without knowing anything about the base
class(es)'s constructor arguments. But that doesn't mean it's impossible:
```
class Foo:
foo: int
def __init__(self):
self.foo = 5
class Bar(Foo):
bar: int
def __init__(self, *args, **kwargs):
if 'bar' in kwargs:
self.bar = kwargs.pop('bar')
else:
*args, self.bar = args
super().__init__(*args, **kwargs)
print([Bar(1), Bar(bar=1)])
```
Essentially, Bar.__init__ looks for a keyword argument named 'bar', and if that
doesn't exist, it uses the last positional argument as the value for 'bar'.
This is backwards compatible with "normal" dataclasses, and improves support
for dataclasses with custom __init__s.
----------
_______________________________________
Python tracker <[email protected]>
<https://bugs.python.org/issue43835>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com