Skip to content

Instantly share code, notes, and snippets.

@jaantollander
Last active March 9, 2023 02:17
Embed
What would you like to do?
Template for Python decorator function and class
import functools
def decorator(function):
"""A general decorator function"""
@functools.wraps(function)
def wrapper(*args, **kwargs):
# Write decorator function logic here
# Before function call
# ...
result = function(*args, **kwargs)
# After function call
# ...
return result
return wrapper
def decorator_with_args(func=None, *, arg=None):
"""Decorator function with arguments
Decorator can be used with or without arguments
Examples:
>>>
>>> @decorator_with_args
>>> def func():
>>> pass
>>>
>>> @decorator_with_args(arg='foo')
>>> def func():
>>> pass
>>>
"""
# 1. Decorator arguments are applied to itself as partial arguments
if func is None:
return functools.partial(decorator_with_args, arg=arg)
# 2. logic with the arguments
...
# 3. Handles the actual decorating
@functools.wraps(func)
def wrapper(*args, **kwargs):
# Write decorator function logic here
# Before function call
# ...
result = func(*args, **kwargs)
# After function call
# ...
return result
return wrapper
class decorator_class(object):
"""General decorator class"""
def __init__(self, *args, **kwargs):
"""Decorator arguments"""
pass
def __call__(self, function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
# Write decorator function logic here
# Before function call
# ...
result = function(*args, **kwargs)
# After function call
# ...
return result
return wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment