On Mon, May 2, 2022 at 9:30 PM Joao S. O. Bueno <[email protected]>
wrote:
> Anyway, there is something dataclasses do today that prevent you from jsut
> adding a @dataclass for binding __init__ attributes from an otherwise
> "complete class that does things":
>
I nor anyone else ever claimed dataclasses could be used for everything.
You are quite right that you can’t make a dataclass that subclasses a
non-dataclass— particularly when the subclass takes fewer parameters in its
__init__. But that’s a bit of an anti-pattern anyway.
In [17]: from dataclasses import dataclass
>
> In [18]:
>
> In [18]: @dataclass
> ...: class A:
> ...: a: int
> ...: def __post_init__(self, **kwargs):
> ...: print(kwargs)
> ...:
>
> In [19]: A(1, b=3)
> ---------------------------------------------------------------------------
> TypeError Traceback (most recent call
> last)
> Input In [19], in <cell line: 1>()
> ----> 1 A(1, b=3)
>
> TypeError: A.__init__() got an unexpected keyword argument 'b'
>
Why would you not write that as:
@dataclass
class A:
a: int
b: int
def __post_init__(self, **kwargs):
print(kwargs)
If you really don't want b, you could remove it in the __post_init__ -- but
as stated earlier in this thread, dataclasses are not a good idea if you
have to do a lot of hand-manipulation -- you might as well write a standard
class.
And if you are subclassing, and need to have a parameter passed on to the
superclass, you need to deal with that by hand anyway:
class A(B):
def __init__(self, a):
super.__init__(a, b)
is clearly not going to work, so you do:
class A(B):
def __init__(self, a, b):
super.__init__(a, b)
unless you do:
class A(B):
def __init__(self, a, *args, **kwags):
super.__init__(a, *args, **kwargs)
which is indeed a common pattern, and not supported by datclasses *yet --
there's talk of adding a way to support **kwargs.
The problem with toy examples is that we can have no idea how best to solve
a non-problem -- so we have no idea if the point being made is valid --
it's a challenge.
But yes, there are many use cases not suited to dataclasses. The question
is how many of these would rap parge benefit from auto-assigning syntax?
I re-iterate that while I'd find this an useful addition,
>
I agree.
> I think new syntax for this would be overkill.
>
And I agree there, too.
-CHB
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/KC6TXDU5YLAXGV426GUXOBPL7QVW5J5V/
Code of Conduct: http://python.org/psf/codeofconduct/