On 4/15/2020 1:52 PM, Ricky Teachey wrote:
Therefore, it seems weird for __init__ not to call super.
I was not part of it, but I know this was heavily discussed during the
development of dataclasses prior to 3.7, and it was decided not to do
this, at least at THAT time (not saying that can't change, but there
were reasons). If Eric V Smith is about I'm sure he could provide
insight, or links to the relevant conversations.
Sorry, I've been tied up on other things.
In general, it's not possible to know how to call super.__init__() if
you don't a priori know the arguments it takes. That's why dataclasses
doesn't guess. The only general-purpose way to do it is to use *args and
**kwargs. Since a goal of dataclasses is to use good typing information
that works with type checkers, that seems to defeat part of the purpose.
One thing you could do in this scenario is to use a classmethod as an
"alternate constructor". This basically gives you any post- and pre-
init functionality you want, using any regular parameters or *args and
**kwargs as fits your case. This example shows how to do it with *args
and **kwargs, but you could just as easily do it with known param names:
from dataclasses import dataclass
class BaseClass:
def __init__(self, x, y):
print('initializing base class', x, y)
self.x = x
self.y = y
@dataclass
class MyClass(BaseClass):
a: int
b: int
c: int
@classmethod
def new(cls, a, b, c, *args, **kwargs):
self = MyClass(a, b, c)
super(cls, self).__init__(*args, **kwargs)
return self
c = MyClass.new(1, 2, 3, 10, 20)
print(c)
print(c.x, c.y)
If you got really excited about it, you could probably write a decorator
to do some of this boilerplate for you (not that there's a lot of it in
this example). But I don't think this would get added to dataclasses itself.
To Brett's point: has anyone looked to see what attrs does here? When
last I looked, they didn't call any super __init__, but maybe they've
added something to address this.
Eric
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/python-ideas@python.org/message/I72ZMHYLTQO46YZUCJG2GLRQMLIMJR4B/
Code of Conduct: http://python.org/psf/codeofconduct/