For loop extended syntax

Terry Reedy tjreedy at udel.edu
Mon Mar 21 20:51:42 EST 2005


"George Sakkis" <gsakkis at rutgers.edu> wrote in message 
news:3a8qnmF66bha6U1 at individual.net...
> A generalization of the 'for .. in' syntax that would handle
> extra arguments the same way as functions would be:
>
> for (x,y,z=0,*rest) in (1,2,3), (3,4), (5,6,7,8):
>     print x, y, z, rest
>
> I'd love to see this in python one day; it is pretty obvious
> what it would do for anyone familiar with function argument tuples.

Jeff covered the obvious objection that this is a change from assignment 
sematics to function call semantics.  Slightly less obvious is that this 
will slow down everyone's for loops for the benefit of the very few who 
would want to do such a thing.  (Is the above based on a real use case?) 
Python function calls are 'slow' (relative to assignment, certainly) in 
part *because* of the great flexibility in call signatures.

In any case, one can now write (with hardcoded format and types, untested):

def argify(*tups):
  for tup in tups:
    ltup = len(tup)
    if    ltup >= 4: yield tup[0:3] + (tup[3:],)
    elif ltup == 3: yield tup + ((),)
    elif ltup == 2: yield tup + (0, ())
    else:                raise TypeError("Tuple %s needs at least 2 items" 
% (tup,)

for x,y,z,rest in argify(....): print x,y,x,rest

Terry J. Reedy

 






More information about the Python-list mailing list