6

I was wondering if it's possible to use star unpacking with own classes rather than just builtins like list and tuple.

class Agent(object):
    def __init__(self, cards):
        self.cards = cards
    def __len__(self):
        return len(self.cards)
    def __iter__(self):
        return self.cards

And be able to write

agent = Agent([1,2,3,4])
myfunc(*agent)

But I get:

TypeError: visualize() argument after * must be a sequence, not Agent

Which methods do I have to implement in order to make unpacking possible?

Sebastian Wozny
  • 16,943
  • 7
  • 52
  • 69
  • 6
    Your `__iter__` should return an iterator over your cards, not the length of them. – kindall May 23 '16 at 20:46
  • 1
    Possible duplicate of [How to make class iterable?](http://stackoverflow.com/questions/19151/how-to-make-class-iterable) – Łukasz Rogalski May 23 '16 at 20:47
  • 1
    @Rogalski I disagree this is a duplicate, it's non-obvious that making it iterable solves the star-unpacking issue (though it does). – Andy Hayden May 23 '16 at 20:53

1 Answers1

10

The exception message:

argument after * must be a sequence

should really say, argument after * must be an iterable.

Often star-unpacking is called "iterable unpacking" for this reason. See PEP 448 (Additional Unpacking Generalizations) and PEP 3132 (Extended Iterable Unpacking).

Edit: Looks like this has been fixed for python 3.5.2 and 3.6. In future it will say:

argument after * must be an iterable


In order to have star unpack, your class must be an iterable i.e. it must define an __iter__ that returns an iterator:

class Agent(object):
    def __init__(self, cards):
        self.cards = cards
    def __len__(self):
        return len(self.cards)
    def __iter__(self):
        return (card for card in self.cards)

then:

In [11]: a = Agent([1, 2, 3, 4])

In [12]: print(*a)  # Note: in python 2 this will print the tuple
1 2 3 4
Andy Hayden
  • 359,921
  • 101
  • 625
  • 535
  • This bug was fixed in January! https://github.com/python/cpython/blob/1123d9a07b4ab916e4d800308053980bcf8dbd57/Python/ceval.c#L5038-L5039 – Andy Hayden May 24 '16 at 02:24