Can my own objects support tuple unpacking?

Scott David Daniels Scott.Daniels at Acm.Org
Thu Mar 27 00:04:23 EDT 2008


Patrick Toomey wrote:
> ... 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
Scott.Daniels at Acm.Org



More information about the Python-list mailing list