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

Greg Ewing greg at cosc.canterbury.ac.nz
Tue Oct 30 04:30:11 CET 2001

Rainer Deyke wrote:
> tuple((a, b)) = 3, 4 # Syntax error.

What if, instead of just the special built-in constructors
() and [], you were allowed *any* constructor on the LHS?


  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.

Greg Ewing, Computer Science Dept, University of Canterbury,	  
Christchurch, New Zealand
To get my email address, please visit my web page:	  

More information about the Python-list mailing list