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: lambda issue in for-loop
Type: behavior Stage: resolved
Components: Interpreter Core Versions: Python 3.10, Python 3.9
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: christian.heimes, steven.daprano, vincent7f
Priority: normal Keywords:

Created on 2021-10-14 12:20 by vincent7f, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Files
File name Uploaded Description Edit
test8.py vincent7f, 2021-10-14 12:20
Messages (3)
msg403899 - (view) Author: Vincent Liang (vincent7f) Date: 2021-10-14 12:20
Strange behavior is found when lambda is used inside for-loop.

code:(same as attached file)

# begin of CODE
def aa(x):
    print("aa")
def bb(x):
    print("bb")

namefun = [
    ("a", aa),
    ("b", bb),
]
name2fun = {}
for name, fun in namefun:
    name2fun[name] = lambda x: fun(x)
# issue happened when calling lambda
name2fun["a"](1)
name2fun["b"](1)
# end of CODE

output:
bb
bb

expected output:
aa
bb
msg403901 - (view) Author: Christian Heimes (christian.heimes) * (Python committer) Date: 2021-10-14 12:53
You are running in a typical scope issue. The local and global scope of a lambda work differently than you expect. You can work around the issue by making fun a local variable:

for name, fun in namefun:
    name2fun[name] = lambda x, fun=fun: fun(x)
msg403902 - (view) Author: Steven D'Aprano (steven.daprano) * (Python committer) Date: 2021-10-14 12:54
See also the FAQs:

https://docs.python.org/3/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result
History
Date User Action Args
2022-04-11 14:59:51adminsetgithub: 89632
2021-10-14 12:54:12steven.dapranosetnosy: + steven.daprano
messages: + msg403902
2021-10-14 12:53:20christian.heimessetstatus: open -> closed

nosy: + christian.heimes
messages: + msg403901

resolution: not a bug
stage: resolved
2021-10-14 12:20:21vincent7fcreate