Skip to content

Instantly share code, notes, and snippets.

@cespare
Created April 4, 2011 17:49
Show Gist options
  • Save cespare/902063 to your computer and use it in GitHub Desktop.
Save cespare/902063 to your computer and use it in GitHub Desktop.
Python lambda gotcha
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