Unpacking extension (Re: A small inconsistency in syntax?)

James_Althoff at i2.com James_Althoff at i2.com
Tue Oct 30 12:54:41 EST 2001


Greg Ewing wrote:
>What if, instead of just the special built-in constructors
>() and [], you were allowed *any* constructor on the LHS?
>
>Consider:
>
>  class Pair:
>    def __init__(self, x, y):
>      self.x = x
>      self.y = y
>    def __unpack__(self):
>      return x, y
>
>  p = Pair(17, 42)
>  Pair(a, b) = p
>
>which should result in a == 17, b == 42.
>
>More precisely, when the LHS is of the form
>
>   <expression evaluating to a class>(pattern, ...)
>
>the RHS is checked to ensure it is an instance of the
>LHS class (raising an exception otherwise), and its
>__unpack__ method is called to produce a sequence which
>is then unpacked into the argument patterns.

Did you mean

def __unpack__(self):
    return self.x, self.y

Otherwise, what are the x and y referring to?

And is Pair(a,b) on the LHS any *callable*?  Or must the object Pair be a
type object or class object only?

Jim






More information about the Python-list mailing list