Created
April 4, 2011 17:49
-
-
Save cespare/902063 to your computer and use it in GitHub Desktop.
Python lambda gotcha
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def callback(message): | |
print(message) | |
foo = ["a", "b", "c"] | |
# Environment variables are only captured as references by the lambda: | |
bar = [lambda: callback(s) for s in foo] | |
for f in bar: | |
f() # => c x 3 | |
# Arguments are saved in the lambda's scope: | |
bar = [lambda t = s: callback(t) for s in foo] | |
for f in bar: | |
f() # => a, b, c | |
# It also will work if you switch to a generator, because the following three things happen sequentially: | |
# * Next value of foo is found | |
# * Lambda is created | |
# * Lambda is evaluated (while s still contains the expected value). | |
bar = (lambda: callback(s) for s in foo) | |
for f in bar: | |
f() # => a, b, c |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment