Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

star unpacking for own classes

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?

like image 203
Sebastian Wozny Avatar asked May 23 '16 20:05

Sebastian Wozny


People also ask

How do you unpack a set in Python?

Unpacking in Python refers to an operation that consists of assigning an iterable of values to a tuple (or list ) of variables in a single assignment statement. As a complement, the term packing can be used when we collect several values in a single variable using the iterable unpacking operator, * .

What is the significance of unpacking the element in tuple through asterisk (*) Explain with example?

Using Asterisk * If the asterisk is added to another variable name than the last, Python will assign values to the variable until the number of values left matches the number of variables left.

What unpacking operator would you use to unpack a dictionary passed to a function?

While a single asterisk is used to unpack lists and tuples, the double-asterisk (**) is used to unpack dictionaries.

How do I unpack a string in Python?

Method : Using format() + * operator + values() The * operator is used to unpack and assign. The values are extracted using values().


1 Answers

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
like image 180
Andy Hayden Avatar answered Sep 26 '22 21:09

Andy Hayden