Skip to content

Instantly share code, notes, and snippets.

@slor
Created December 21, 2011 23:09
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 slor/1508130 to your computer and use it in GitHub Desktop.
Save slor/1508130 to your computer and use it in GitHub Desktop.
An example and explaination of a Python decorator that takes a non-optional parameter.
""" An example of writing a decorator that takes an argument.
Based on e-satis's answer at http://stackoverflow.com/questions/739654/understanding-python-decorators#1594484.
"""
from functools import wraps
# The outer-most level is the decorator factory. The middle level is the
# decorator and the inner most level is where we call the decorated function.
def decorator_maker(buzz):
""" Returns a decorator.
If buzz is True, then will make decorated functions say 'BUZZ!'.
"""
def dec(func):
""" Decorates a function. """
# Use wraps() to preserve information about the wrapped function.
@wraps(func)
def wrapper(*args, **kwargs):
""" Calls the decorated (wrapped) function. """
if buzz:
print "BUZZ!"
return func(*args, **kwargs)
return wrapper
return dec
if __name__ == '__main__':
# These below are progressivly more compact ways to achieve the decoration
# effect w/o using @decorator syntax. For illustration only.
def func(x, y=None):
print x, y
decorator = decorator_maker(True)
decorated_func = decorator(func)
decorated_func(1, y=2)
decorated_func = decorator_maker(True)(func)
decorated_func(1, y=2)
decorator_maker(True)(func)(1, y=2)
# This below is how to call the decorator w/ optional args.
@decorator_maker(True)
def func2(x, y=None):
print x, y
func2(1, y=2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment