Skip to content

Instantly share code, notes, and snippets.

@mtth
Created March 10, 2014 02:17
Show Gist options
  • Save mtth/9458430 to your computer and use it in GitHub Desktop.
Save mtth/9458430 to your computer and use it in GitHub Desktop.
Late variable binding in python
#!/usr/bin/env python
# encoding: utf-8
"""Testing late binding of variables."""
# last value of j is used everywhere
bars = [lambda i: j * i for j in range(5)]
assert all(b(1) == 4 for b in bars), "for lambda functions"
bazs = []
for j in range(5):
def baz(i):
return i * j
bazs.append(baz)
assert all(b(1) == 4 for b in bazs), "and normal functions"
# not here since j is passed by value to foo
def foo(j):
def _foo(i):
return j * i
return _foo
foos = [foo(j) for j in range(5)]
assert not all(b(1) == 4 for b in foos), "but not here"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment