Parameterized functions of no arguments?

Hrvoje Niksic hniksic at xemacs.org
Fri Feb 11 15:43:25 CET 2011


Chris Rebert <clp2 at rebertia.com> writes:

> It's a well-known problem due to the intricacies of Python's scoping
> rules.

Actually, it is not specific to Python's scoping rules (which mandate
local, then module-level, then built-in name lookup).  The root of the
surprise is, as you correctly point out, the fact that the variable's
"cell" is shared by all iterations through the loop.  Taking that into
account, it logically follows that all enclosed functions end up reading
the same value.

This is not endemic to Python, the exact same surprise is present in
Common Lisp, a language with long tradition of closures and otherwise
radically different scoping rules.

* (setq l (loop for i from 1 to 10 collect (lambda () i)))
* (mapcar #'funcall l)
(11 11 11 11 11 11 11 11 11 11)



More information about the Python-list mailing list