Unpacking extension (Re: A small inconsistency in syntax?)
Bernhard Herzog
bh at intevation.de
Tue Oct 30 14:29:26 EST 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?
> >
> >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
What's wrong with e.g.
class Pair:
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,
anyway, IMO.
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.
Bernhard
--
Intevation GmbH http://intevation.de/
Sketch http://sketch.sourceforge.net/
MapIt! http://mapit.de/
More information about the Python-list
mailing list