On this page
python decorators
Prev: python functions | Up: python3 | Next: python metaprogramming
Rel: python3, python functions, python metaprogramming, Decorators and Closures, property, functools
Ref: docs.python.org — functools.wraps | Real Python — Primer on Python Decorators
Tags: #public #python3 #decorators
Import
from functools import wraps, partial
Overview
A decorator is a higher-order function that takes a function, wraps its behavior, and returns the wrapper function. @functools.wraps(func) preserves the original function's __name__, __doc__, and metadata.
from functools import wraps
def add_two(func):
@wraps(func)
def inner(*args, **kwargs):
return func(*args, **kwargs) + 2
return inner
@add_two
def prod_five():
return 5
>>> prod_five()
7
Stacked Decorators
Stacked decorators wrap from bottom to top and execute from top to bottom:
def wrap_in_x(func):
@wraps(func)
def inner(*args, **kwargs):
print("x" * 10)
func(*args, **kwargs)
print("x" * 10)
return inner
def wrap_in_y(func):
@wraps(func)
def inner(*args, **kwargs):
print("y" * 10)
func(*args, **kwargs)
print("y" * 10)
return inner
@wrap_in_x
@wrap_in_y
def greet(msg):
print(msg)
Common Decorator Recipes
Timing Decorator (@timeit)
import time
from functools import wraps
def timeit(func):
"""Decorator to time a function execution."""
@wraps(func)
def time_wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
total = time.time() - start
print(f'func:{func.__name__} args:{[args, kwargs]} took: {total:.4f}s')
return result
return time_wrapper
Debug Decorator with Optional Arguments (@debug)
from functools import partial, wraps
def debug(func=None, *, prefix=''):
if func is None:
return partial(debug, prefix=prefix)
msg = prefix + func.__qualname__
@wraps(func)
def wrapper(*args, **kwargs):
print(msg)
return func(*args, **kwargs)
return wrapper
Linked from
Related notes
- tuts/python3/tutorials/advanced_python_internals/decorators_and_closures Linked here; links to this page; shared tags: #decorators
- tuts/python3 Linked here; links to this page
- tuts/python3/python functions Linked here; links to this page
- tuts/python3/python metaprogramming Linked here; links to this page
- tuts/python3/__builtins__/property Linked here
- tuts/python3/stdlib_module/functools Linked here
- tuts/python3/tutorials links to this page
- tuts/python3/tutorials/advanced_python_internals links to this page
- tuts/python3/tutorials/core_fundamentals/functions links to this page