[Python-ideas] Consider adding an iterable option to dataclass
levkivskyi at gmail.com
Mon Aug 13 07:08:29 EDT 2018
On 11 August 2018 at 01:29, Eric V. Smith <eric at trueblade.com> wrote:
> On 8/10/2018 7:01 PM, Neil Girdhar wrote:
>> sequence would simply inherit from collections.abc.Sequence and implement
>> the two methods __len__ and __getitme__.
> Unless I'm misunderstanding you, this falls in to the same problem as
> setting __slots__: you need to return a new class, in this case since you
> can't add inheritance after the fact. I don't think __isinstancecheck__
> helps you here, but maybe I'm missing something (I'm not a big user of
> inheritance or ABCs).
Here are three points to add:
1. collections.abc.Sequence doesn't have a __subclasshook__, i.e. it
doesn't support structural behaviour. There was an idea as a part of PEP
544 to make Sequence and Mapping structural, but it was rejected after all.
2. Mutating __bases__ doesn't require creating a new class. So one can just
add Sequence after creation. That said, I don't like this idea, `typing`
used to do some manipulations with bases, and it caused several confusions
and subtle bugs, until it was "standardised" in PEP 560.
3. In my experience with some real life code the most used tuple API in
named tuples is unpacking, for example:
for id, name in rows:
I proposed to add it some time ago in
https://github.com/ericvsmith/dataclasses/issues/21, it will be enough to
just generate an __iter__ (btw such classes will be automatically
subclasses of collections.abc.Iterable, which is structural):
origin = Point(0, 0)
x, y = origin
But this idea was postponed/deferred. Maybe we can reconsider it?
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-ideas