Created
January 14, 2019 23:28
-
-
Save wware/3a11b5086838b3f0c0df1fc36baa0529 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
""" | |
There is an unfortunate thing about Python scoping. You can't easily access the variables | |
of a calling function (as you can do in Scheme) so if you want to use those variables you | |
need to jump thru silly hoops. See | |
https://stackoverflow.com/questions/15608987/access-variables-of-caller-function-in-python | |
The nice thing about using a caller's variables is that it provides a nice way to do closures. | |
Variable access in closures will work OK as long as you are not ASSIGNING the variable. In | |
this case, we assign indices of "scope" but we never assign scope itself -- if we did, Python | |
would conclude that scope belongs to stuff, not to make_thing. Annoying. | |
""" | |
def make_thing(): | |
internal_vbl = 0 | |
scope = locals() | |
def stuff(): | |
scope['internal_vbl'] += 1 | |
return scope['internal_vbl'] | |
return stuff | |
f = make_thing() | |
for _ in range(5): | |
print f() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment