[New-bugs-announce] [issue27673] lambda function in loop

Stefan Rosewig report at bugs.python.org
Wed Aug 3 07:39:41 EDT 2016


New submission from Stefan Rosewig:

Trying to build tkinter menu dynamically by reading an ini file (configparser) I detect an issue with the lambda function used inside a loop. 
If the loop variable is used as option in the lambda function, the lambda is not place in time using the current value, all functions are created when leaving the calling function using the last value of the loop variable. 
There is a simple workaround, just use a separate function to add the menu-item. 
The attached demo shows both, the "Working" menu which was created by a function and does what was expected and the "Failure" menu which was created inside the loop itself and doesn't do what was expected.
Since the problem is not bound to configparser I used a simple loop walking through a list of menu item names to simulate the reasing of an ini file. Inside the loop a menu item with the name is appende to the Failure menu calling lambda:cmd(name) as command. Also a function is called uding the name as parameter wich appends a Menu item to the Working menu using the identic options as for Failure menu.
When the loop is finidhed the value of teh loop variable is set to "senseless" which should have no effect.
The function cmd(param) just appends a string including the param value to the output.
if the script is started the menus ar built and look identical but if you click on a Working menu item the name of the item is printed. if you click on the Failure menu item "senseless" is printed for each item which is the value I set after the loop.

>From my point of view all lambda commands are build when the calling function is left using the value of the variable at this time. this lead in the demo  attached to identic function calls for the Failure menu. For the working menu a separate function is called and the lambda is build at the end of this function which leads to the expected behaviour.

I'm running Python 3.5.2 (v3.5.2:4def2a2901a5) 64 Bit on Windows-10 Pro 64

----------
components: Tkinter
files: lambda-prob.pyw
messages: 271897
nosy: Thaloss66
priority: normal
severity: normal
status: open
title: lambda function in loop
type: behavior
versions: Python 3.5
Added file: http://bugs.python.org/file43989/lambda-prob.pyw

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


More information about the New-bugs-announce mailing list