[Python-ideas] Consider adding an iterable option to dataclass
Eric V. Smith
eric at trueblade.com
Fri Aug 10 20:29:37 EDT 2018
On 8/10/2018 7:01 PM, Neil Girdhar wrote:
> It would be nice if dataclasses
> had an option to make them a sequence. This would make
> dataclass(frozen=True, order=True, sequence=True)
> an optionally-typed version of namedtuple. It would almost totally
> supplant it except that namedtuples have a smaller memory footprint.
Note that type.NamedTuple already gives you typed namedtuples.
Admittedly the feature set is different from dataclasses, though.
> 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).
Not that returning a new class is impossible, it's just that I didn't
want to do it in the first go-round with dataclasses.
For slots, I have a sample @add_slots() at
Maybe we could do something similar with @add_sequence() and test it
out? It would have to be a little more sophisticated than @add_slots(),
since it would need to iterate over __dataclass_fields__, etc.
I'm on vacation next week, maybe I'll play around with this.
More information about the Python-ideas