Skip to content

Instantly share code, notes, and snippets.

@jaantollander
Last active August 7, 2024 11:54
Show Gist options
  • Save jaantollander/48480cfabbe98a7efe4c9848a5b55e6a to your computer and use it in GitHub Desktop.
Save jaantollander/48480cfabbe98a7efe4c9848a5b55e6a to your computer and use it in GitHub Desktop.
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