Last active
August 7, 2024 11:54
-
-
Save jaantollander/48480cfabbe98a7efe4c9848a5b55e6a to your computer and use it in GitHub Desktop.
Template for Python decorator function and class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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