Skip to content

Instantly share code, notes, and snippets.

Last active February 28, 2023 04:18
What would you like to do?
Python iiterable
from dataclasses import dataclass
class Person:
name: str
age: int
city: str
def __iter__(self):
self._fields = [ for field in self.__dataclass_fields__.values()]
self._index = 0
return self
def __next__(self):
if self._index == len(self._fields):
raise StopIteration
field = self._fields[self._index]
value = getattr(self, field)
self._index += 1
return value
person = Person("John", 25, "New York")
for prop in person:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment