Unpacking extension (Re: A small inconsistency in syntax?)
Quinn Dunkan
quinn at retch.ugcs.caltech.edu
Wed Oct 31 01:15:18 EST 2001
On Tue, 30 Oct 2001 16:30:11 +1300, Greg Ewing <greg at cosc.canterbury.ac.nz>
wrote:
>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?
>
>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.
...and, by extension:
class Pair:
...
def __eq__(self, Pair(x, y)):
return self.x == x and self.y == y
But then, since the symbol 42 is just a nullary constructor for the integer
42, this would also allow:
def f(x, 42):
...
and
42 = y
Now we have a way to write type checks:
def f(int(x), str(y)):
... # just a stopgap until 'f :: int -> str -> ..' makes it's debut <wink>
And, of course, just for sentimental value:
def fact(n + 1):
if n == 1:
return 1
else:
return (n+1) * fact(n)
Naturally it all works much better once you introduce function overloading:
def fact(1):
return 1
def fact(n + 1):
return (n+1) * fact(n)
More information about the Python-list
mailing list