Last active
August 29, 2015 13:56
-
-
Save wolever/9060937 to your computer and use it in GitHub Desktop.
Fun with Python scopes
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
global_var = 42 | |
def outer_func(): | |
outer_var = 21 | |
un_used_outer_var = 16 | |
def inner_func(): | |
inner_var = 7 | |
def inner_inner_func(): | |
inner_inner_var = 3 | |
# note: the outer_var must be explicitly referenced, otherwise it won't | |
# be added to the list of co_freevars. Notice that 'un_used_outer_var' | |
# doesn't get shown anywhere. | |
inner_var | |
outer_var | |
# note, though, that the global_var is *not* added to the freevars | |
global_var | |
print "inner inner locals:", locals() | |
return inner_inner_func | |
inner_inner_func = inner_func() | |
inner_inner_func() | |
print "inner inner freevars:", dict(zip( | |
inner_inner_func.func_code.co_freevars, | |
[ c.cell_contents for c in inner_inner_func.func_closure ], | |
)) | |
print "inner freevars:", dict(zip( | |
inner_func.func_code.co_freevars, | |
[ c.cell_contents for c in inner_func.func_closure ], | |
)) | |
outer_func() | |
""" | |
Result: | |
inner inner locals: {'inner_var': 7, 'inner_inner_var': 3, 'outer_var': 16} | |
inner inner freevars: {'inner_var': 7, 'outer_var': 16} | |
inner freevars: {'outer_var': 16} | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment