Can my own objects support tuple unpacking?

Patrick Toomey ptoomey3 at mac.com
Wed Mar 26 23:33:01 EDT 2008


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




More information about the Python-list mailing list