Unpacking extension (Re: A small inconsistency in syntax?)
bh at intevation.de
Tue Oct 30 20:29:26 CET 2001
James_Althoff at i2.com writes:
> Greg Ewing wrote:
> >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
What's wrong with e.g.
def __init__(self, x, y):
self.x = x
self.y = y
def __getitem__(self, index):
return (self.x, self.y)[index]
p = Pair(17, 42)
a, b = p
That works today (just tested with 2.1 and 1.5.2).
The only thing it doesn't do is checking whether p is an instance of
Pair as your proposal would but that's better done with a separate test,
AFAIK, the "[a,b] = sequence" syntax is a holdover of some old python
version (<= 1.4 IIRC) where "a, b = sequence" would only work for tuples
and "[a,b] = sequence" only for lists.
Personally, I wouldn't mind to see the "[a,b] = sequence" sytax go.
Intevation GmbH http://intevation.de/
More information about the Python-list