[issue13652] Creating lambda functions in a loop has unexpected results when resolving variables used as arguments

WIl Hall report at bugs.python.org
Thu Dec 22 21:25:27 CET 2011


New submission from WIl Hall <wil at wilhall.com>:

When creating lambda functions in a loop, variables involved in the lambda statements appear to not resolve until the loop finishes. This results in all of the defined lambda functions using the same variable to resolve to the last value of that variable.

For example, in my test program attached, I loop through a list of words: ["one", "two", "three", "four"] and create a function for each word, I.e: lambda: print_word(word). This results in every function having the word "four" as their argument. This doesn't seem like intended behavior.

Im my example program attached, I demonstrate both the intended and not intended behavior - creating the lambda functions in another function, versus creating them in a loop.

----------
components: Interpreter Core
files: lambda_tests.py
messages: 150107
nosy: wilhall
priority: normal
severity: normal
status: open
title: Creating lambda functions in a loop has unexpected results when resolving variables used as arguments
type: behavior
versions: Python 2.6, Python 2.7
Added file: http://bugs.python.org/file24078/lambda_tests.py

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue13652>
_______________________________________


More information about the Python-bugs-list mailing list