* for generic unpacking and not just for arguments?

Tim Chase python.list at tim.thechases.com
Mon Nov 30 11:58:48 EST 2009


> So you want *x behave radically different in subtly different contexts? 
> 
> a, *x, b = iterator
> 
> would give x a list and iterator run to exhaustion, whereas:

Using the infix "*x" I'd be fine with x being an iterator too in 
the same way as the postfix "*x" I'd enjoy, but this would 
require consuming all-but-the-remaining-fixed and the converting 
the middle bits back into an iterator...which isn't that much 
different from the current implementation of "a, *x, b = itr" with

   x = iter(x)

after the tuple assignment.  Not a great gain, but at least 
consistent to remove that burr.

It doesn't allow for infinite generators, but that's a somewhat 
nonsensical request anyways :)  "b = INF"?  "b=-INF"?  "b=K"? 
and it gets weirder with

   a,*x,b,c,d = inf_seq_of_monotonically_increasing_primes()

if you can get me b, c, and d in a finite amount of time, you get 
some sorta prize :)

> However, having some syntax giving the behaviour you want would be nice. 
> Something like this perhaps?
> 
> a, b, c = *iterable
> 
> equivalent to:
> 
> _t = iter(iterable)
> a = next(_t)
> b = next(_t)
> c = next(_t)  # and so on for each of the left-hand names
> del _t
> 
> That would be useful.

But yes, that's even better for my use case, as it lacks the ugly 
"*_" sponge to soak up the remainder and removes my need to track 
the number of items on the LHS of the assignment.  That seems it 
would involve a new Python construct/syntax rather than the 
existing py3k syntax.  Or at least the removal of the 
"ValueError: too many values to unpack" error.  That would be a 
lovely addition (when the new-feature-ban is lifted :)

-tim







More information about the Python-list mailing list