Created
March 10, 2014 02:17
-
-
Save mtth/9458430 to your computer and use it in GitHub Desktop.
Late variable binding in python
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
#!/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