-
-
Save mwhooker/6303778 to your computer and use it in GitHub Desktop.
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
class A(object): | |
def hook(self, f): | |
atime = 0 | |
def intime(*args): | |
print atime | |
atime += 1 | |
return f(*args) | |
return intime | |
>>> f = A().hook(lambda b: b + 1) | |
>>> f(1) | |
Traceback (most recent call last): | |
File "<stdin>", line 1, in <module> | |
File "<stdin>", line 5, in intime | |
UnboundLocalError: local variable 'atime' referenced before assignment | |
>>> |
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 python3 | |
class A(object): | |
def hook(self, f): | |
atime = 0 | |
def intime(*args): | |
nonlocal atime | |
print(atime) | |
atime += 1 | |
return f(*args) | |
return intime | |
f = A().hook(lambda b: b + 1) | |
# works as expected | |
for i in range(10): | |
f(i) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment