unintuitive for-loop behavior

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Sat Oct 1 04:44:13 EDT 2016


Steve D'Aprano writes:

> In a language like Python, the only distinction we can make between
> name bindings is, which namespace is the binding in? In other words,
> what is the current block of code's scope?

Python already has nested scopes. A local scope for just those variables
introduced in for-loops could be carved out as in the following example.

The following example function has three parameters and two local
variables, one of which is only assigned inside the loop (and it also
references one global variable), in addition to the variable introduced
in the loop.

def eg(wev, a, b):
   y = 0
   for x in wev: # to be given a new semantics
       f(a, x)
       f(x, b)
       y += 1
       z = (y > 12)
   return y, z

Replace the loop with a call to a thunk that refers to the variables in
the outer scopes, except for the one variable that the loop introduces -
that variable is to be local to the thunk. So the example function
should be equivalent to something like the following translation.

def eg(wev, a, b):
   y = 0
   def g31():
       nonlocal y, z # the assigned variables
       g32 = iter(wev)
       while 1: # need to catch StopIteration
          x = next(g32) # now local to g31
          f(a, x)
          f(x, b)
          y += 1
          z = (y > 12)
   g31()
   return y, z

A different translation would introduce each x in a different function
for each step in the iteration. That's just a variation on the overall
theme.



More information about the Python-list mailing list