This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Creating lambda functions in a loop has unexpected results when resolving variables used as arguments
Type: behavior Stage:
Components: Interpreter Core Versions: Python 2.7, Python 2.6
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: mrabarnett, wilhall
Priority: normal Keywords:

Created on 2011-12-22 20:25 by wilhall, last changed 2022-04-11 14:57 by admin. This issue is now closed.

Files
File name Uploaded Description Edit
lambda_tests.py wilhall, 2011-12-22 20:25 Lambda Function Tests
Messages (3)
msg150107 - (view) Author: WIl Hall (wilhall) Date: 2011-12-22 20:25
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.
msg150109 - (view) Author: Matthew Barnett (mrabarnett) * (Python triager) Date: 2011-12-22 20:59
That's not a bug.

This might help to explain what's going on:

What do (lambda) function closures capture in Python?
http://stackoverflow.com/questions/2295290/what-do-lambda-function-closures-capture-in-python
msg150110 - (view) Author: WIl Hall (wilhall) Date: 2011-12-22 21:04
Makes sense. Misunderstanding on my part, then. Closing as invalid (not a bug).
History
Date User Action Args
2022-04-11 14:57:24adminsetgithub: 57861
2011-12-22 21:04:23wilhallsetmessages: + msg150110
2011-12-22 21:03:17benjamin.petersonsetstatus: open -> closed
resolution: not a bug
2011-12-22 20:59:59mrabarnettsetnosy: + mrabarnett
messages: + msg150109
2011-12-22 20:25:27wilhallcreate