Skip to content

Instantly share code, notes, and snippets.

@wolever
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wolever/9060937 to your computer and use it in GitHub Desktop.
Save wolever/9060937 to your computer and use it in GitHub Desktop.
Fun with Python scopes
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