unintuitive for-loop behavior

Gregory Ewing greg.ewing at canterbury.ac.nz
Fri Sep 30 21:08:20 EDT 2016


Steve D'Aprano wrote:
> What happens if it is *not* a misfeature? Gotchas are not always
> misfeatures -- sometimes gotchas are gotchas because people's expectations
> are simply wrong, and pandering to their confused expectations does not
> actually help them.
> 
> I haven't made up my mind about *this* specific (mis)feature itself.

Here's my analysis of it.

First, some definitions:

Current behaviour: The way for-loop variables currently
interact with nested functions.

Alternative behaviour: A nested function captures a
different instance of the for-loop variable on each
iteration. (But *nothing* else changes; in particular,
the body of the loop is *not* a separate scope.)

The current behaviour is completely useless (or at least it's
useful in in only a vanishingly small proportion of cases).
The alternative behaviour would sometimes be useful.

Nothing would need to change except in the rare case where
the loop variable is referenced by a nested function. You
would only pay for the feature if you used it.

There would be no need for ugly workarounds such as default
argument abuse or introducing another level of nested
function.

As a bonus, the alternative behaviour would be more in
line with people's intuitions.

There are some sharp contrasts here with the default
argument situation. There, the alternative behaviour would
be very wasteful in the majority of cases, and there is
a clean workaround for cases where a mutable default is
needed.

-- 
Greg



More information about the Python-list mailing list