49

I have a class that only contains attributes and I would like packing/unpacking to work on it. What collections.abc should I implement to get this behaviour?

class Item(object):

    def __init__(self, name, age, gender)
        self.name = name
        self.age = age
        self.gender = gender

a, b, c = Item("Henry", 90, "male")

I would like to avoid using a namedtuple.

3
  • 4
    You can unpack any Iterable, so you need to implement __iter__.
    – jonrsharpe
    Commented Jun 15, 2016 at 13:57
  • 3
    That depends on whether you want __iter__ to return self or not - you could just return iter((self.name, self.age, self.gender)), for example. It must be iterable, but not necessarily an iterator.
    – jonrsharpe
    Commented Jun 15, 2016 at 14:01
  • Okay thanks I think I got it.
    – Har
    Commented Jun 15, 2016 at 14:03

3 Answers 3

53

You can unpack any Iterable. This means you need to implement the __iter__ method, and return an iterator. In your case, this could simply be:

def __iter__(self):
    return iter((self.name, self.age, self.gender))

Alternatively you could make your class an Iterator, then __iter__ would return self and you'd need to implement __next__; this is more work, and probably not worth the effort.

For more information see What exactly are Python's iterator, iterable, and iteration protocols?


Per the question I linked above, you could also implement an iterable with __getitem__:

def __getitem__(self, index):
    return (self.name, self.age, self.gender)[index]
2
  • 1
    For a generic shallow unpacking (which is what you might want) use: def __iter__(self): return iter(tuple(getattr(self, field.name) for field in dataclasses.fields(self))).
    – Adi Shavit
    Commented May 27, 2022 at 7:04
  • 1
    @AdiShavit that's not so relevant to this answer, which isn't about dataclasses
    – jonrsharpe
    Commented May 27, 2022 at 7:08
29

A better option for unpacking Python 3.7+ dataclasses is as follows:

from dataclasses import astuple, dataclass

@dataclass 
class Item:
    name: str
    age: int
    gender: str

    def __iter__(self):
        return iter(astuple(self))

a, b, c = Item("Henry", 90, "male")
7
  • 1
    True--I just copied the example above. Fixed.
    – Keith
    Commented Jan 19, 2022 at 17:37
  • 5
    Unfortunately, dataclasses.astuple() does deep unpacking which is often undesirable for nested structures -- (see stackoverflow.com/a/51802661/1190077 ).
    – Hugues
    Commented Apr 14, 2022 at 18:44
  • 1
    @AdiShavit why make the tuple then the iterator? Just return the generator expression. You could add this as another answer.
    – jonrsharpe
    Commented May 27, 2022 at 7:26
  • 3
    Simpler and faster shallow unpacking def __iter__(self): return iter(self.__dict__.values())
    – crizCraig
    Commented Jun 29, 2022 at 22:33
  • 2
    self.__dict__.values() may not work if the dataclass is defined to use slots--a feature added in 3.10.
    – Keith
    Commented Mar 22, 2023 at 22:23
6

Another option would be a named tuple

Item = collections.namedtuple('Item', ['name', 'age', 'gender']) 

So this works out of the box:

a, b, c = Item("Henry", 90, "male")

If you're on Python 3.7+, you could also take advantage of dataclasses which are more powerful. But you would need to explicitly call astuple:

@dataclasses.dataclass
class Item(object):
    name: str
    age: int
    gender: str

a, b, c = dataclasses.astuple(Item("Henry", 90, "male"))
6
  • 1
    The named tuple can also be used as an (anonymous) base class, should you want to add other methods to the class. class Item(collections.namedtuple('Item', ['name', 'age', 'gender'])): ...
    – chepner
    Commented Jan 2, 2020 at 20:29
  • @chepner That is nice. I also added a similar solution with dataclasses, but they require you to be a bit more explicit
    – JBernardo
    Commented Jan 2, 2020 at 20:32
  • 4
    The question literally says "I would like to avoid using a namedtuple".
    – wim
    Commented Jan 2, 2020 at 20:38
  • @wim Sigh. I suggested he post the answer here since stackoverflow.com/q/59568853/1126841 was closed as a duplicate of this one. Maybe I should reopen that question, and the answer can be posted there?
    – chepner
    Commented Jan 2, 2020 at 20:46
  • @wim I had added a 2nd solution with data classes, so I find it is petty to complain about it. In any case, I was providing a solution to a similar question that was closed instead
    – JBernardo
    Commented Jan 3, 2020 at 12:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.