Skip to content

Instantly share code, notes, and snippets.

@stonecharioteer
Last active October 22, 2021 14:37
Show Gist options
  • Save stonecharioteer/606e0f59c906cfd0f3f20610723910db to your computer and use it in GitHub Desktop.
Save stonecharioteer/606e0f59c906cfd0f3f20610723910db to your computer and use it in GitHub Desktop.
Python Closures - Bangpypers Lightning Talk 2021-10-22
"""Examples to show how Python stores the closure metadata in a decorator.
Know that this information isn't always just attached to a decorator. It could
also be passed around with regular functions, if the conditions match.
That is, if a variable from a higher scope is _referenced_ from a variable in
another scope, which is passed around, then, a __closure__ meta variable is
attached to the object that is passed around, where it has a store of what its
'closure' is.
Tip: Snoop around with dir() and id(), and check the value of __closure__ and
it's cell_contents.
"""
import functools
#{{{ Simple decorator
def decorator_1(func):
def inner_function(*args, **kwargs):
return func(*args, **kwargs)
return inner_function
#}}}
#{{{ Clean decorator
def decorator_2(func):
@functools.wraps(func)
def inner_function(*args, **kwargs):
return func(*args, **kwargs)
return inner_function
#}}}
#{{{ Decorator with extra variables in wrapper
def decorator_3(func):
x = "Some variable"
@functools.wraps(func)
def inner_function(*args, **kwargs):
return func(*args, **kwargs)
return inner_function
#}}}
#{{{ Decorator with exposed non local
def decorator_4(func):
x = "some variable"
@functools.wraps(func)
def inner_function(*args, **kwargs):
print(x)
return func(*args, **kwargs)
return inner_function
#}}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment