Skip to content

Instantly share code, notes, and snippets.

@arcsector
Last active November 6, 2019 07:10
Show Gist options
  • Save arcsector/78254f35ddbf653639973b8208041708 to your computer and use it in GitHub Desktop.
Save arcsector/78254f35ddbf653639973b8208041708 to your computer and use it in GitHub Desktop.
Meta-wrappers are wrappers within wrappers; these allow for nested decorators and nested wrappers
from functools import wraps
# the f argument is a function that we pass
def base_wrapper(f):
# you need this in all wrappers/decorators
@wraps(f)
# the *args and **kwargs allow for passing
# arguments into the wrapped function;
# notice how we define a function within a
# function with a return value, and then
# return that function we defined
def decorated_function(*args, **kwargs):
print("1. login_required here")
return f(*args, **kwargs)
return decorated_function
# creating the meta wrapper and
# defining the meta decorator
def meta_wrapper(f):
# need this again
@wraps(f)
# next we decorate the function that we're
# going to return with the base_wrapper so
# that it is called before this one
@base_wrapper
def decorated_function(*args, **kwargs):
print("2. newwrapper executed here")
return f(*args, **kwargs)
return decorated_function
# decorating change function with meta_wrapper
# will call the base wrapper and the meta wrapper
@meta_wrapper
def change():
print("3. change function executed here")
change()
@arcsector
Copy link
Author

Output

1. login_required here
2. newwrapper executed here
3. change function executed here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment