* for generic unpacking and not just for arguments?

Tim Chase python.list at tim.thechases.com
Sun Nov 29 20:45:18 CET 2009

> The feature is available in Python 3.x:
>>>> a, b, *c = 1, 2, 3, 4, 5
>>>> a, b, c
> (1, 2, [3, 4, 5])
>>>> a, *b, c = 1, 2, 3, 4, 5
>>>> a, b, c
> (1, [2, 3, 4], 5)

This is a nice feature of 3.x but I'm disappointed (especially in 
light of the move to make more things iterators/generators), that 
the first form unpacks and returns a list instead returning the 
unexhausted generator.  There are times I've wanted to write 
something like

   def powers_of_n(n=2):
     p = 0
     while True:
       yield n ** p
       p += 1

   def linear(i=0, step=1):
     while True:
       yield i
       i += step

   CONST_A, CONST_B, CONST_C, *_ = linear()
   OPT_A, OPT_B, OPT_C, *_ = powers_of_n()

because adding another CONST or OPT becomes trivial (just add it 
to the list of names).  I currently have to do something like

   CONST_A, CONST_B, CONST_C = range(3)

and then remember to bump up my range() parameter when I create a 
new value on the left.  It's not bad to see here, but I often 
have times where N>60 constants and tweaking something in an 
alphabetically sorted list may require scrolling to see/remember 
the range() change.

However, because 3.x tries to make a list out of it, this doesn't 
help me at all because my generator is infinite.  Boo.

Diez Roggisch gave me a beautiful (okay, the implementation code 
is a bit ugly, but the final product's simplicity achieves 
elegance) solution to my similar want for 2.x here:



More information about the Python-list mailing list