I add a __iter__
method to many of my dataclasses:
from dataclasses import astuple, dataclass
@dataclass
class Point:
x: float
y: float
def __iter__(self):
return iter(astuple(self))
Edit to note: the above implementation is problematic in many non-trivial cases. See this post for a correct implementation of __iter__
. I see the trickiness of correctly implementing this as a mark in favor of this feature existing.
This allows for tuple unpacking:
>>> p = Point(1, 2)
>>> x, y = p
It would be nice to be able to do this instead:
from dataclasses import dataclass
@dataclass(iter=True)
class Point:
x: float
y: float
I also suspect that this may make the transition from named tuples to dataclasses easier for folks who use named tuples solely for the sake of tuple unpacking.
It also might be nice to be able to set iter=False
in dataclass fields:
@dataclass(iter=True)
class Point:
x: float
y: float
color: str = field(default="black", iter=False)