Can my own objects support tuple unpacking?

P

Patrick Toomey

Hello,
So, I am new to python, but I always like to learn the ins and outs
of a language by trying to understand how everything fits together.
Anyway, I am trying to figure out how tuple unpacking behavior works.
Specifically, what happens when I do the following:

a,b,c,d = e

Is a method called, such as __getitem__ for each index on the left
(0,1,2,3)? I thought this was logical, so I tried coding up similar
to this

class Foo:
def __getitem__(self, index):
print index
return 1

a = Foo()
b,c,d = a

the output is:
0
1
2
3
ValueError: too many values to unpack

So, it seems like something is going on here with __getitem__, but
obviously something is not quite right.

What got me wondering about this was exceptions, as they seem to use
this idiom in some way. As an example, we can do the following:

class Foo(Exception):
def bar():
print "dummy method"

try:
raise Foo('a', 'b', 'c', 'd')
except Foo, e:
a,b,c,d = e

This will successfully unpack the exception arguments, as if e was a
sequence. How are they implementing this functionality? Is this a
special case for exceptions? I guess my overall question is how tuple
unpacking works underneath the covers. Can I implement tuple
unpacking for my own objects?

Thanks,
Patrick
 
S

Scott David Daniels

Patrick said:
... I am trying to figure out how tuple unpacking behavior works....
a,b,c,d = e

Is a method called, such as __getitem__ for each index on the left
(0,1,2,3)? I thought this was logical, ...

class Foo:
def __getitem__(self, index):
print index
return 1

_So_ close.
class Foo(object): # _Never_ use old-style without a reason
def __getitem__(self, index):
print index
if index < 3:
return index * 5 # just to see
raise IndexError('Zapped') # The secret -- run out.

-Scott David Daniels
(e-mail address removed)
 
G

greg

Scott said:
class Foo(object): # _Never_ use old-style without a reason
def __getitem__(self, index):
print index
if index < 3:
return index * 5 # just to see
raise IndexError('Zapped') # The secret -- run out.

Another way is to make your object iterable -- read
up about the "iterator protocol".
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top