On this page
functools.wraps
Prev: functools.update_wrapper | Up: functools
Rel: functools.cache, functools.cached_property, functools.cmp_to_key, functools.lru_cache
Ref: docs.python.org — functools.wraps
Tags: #public #python3 #stdlib #functools
Import
import functools
from functools import wraps
Signature & Overview
functools.wraps(wrapped, assigned=('__module__', '__name__', '__qualname__', '__doc__', '__annotate__', '__type_params__'), updated=('__dict__',))
Decorator factory to apply update_wrapper() to a wrapper function Returns a decorator that invokes update_wrapper() with the decorated function as the wrapper argument and the arguments to wraps() as the
Usage
from functools import wraps
def double_result(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
return fn(*args, **kwargs) * 2
return wrapper
@double_result
def add(a: int, b: int) -> int:
"""Add two ints."""
return a + b
assert add(2, 3) == 10
assert add.__name__ == "add" and add.__doc__ == "Add two ints."
Gotchas
- Always use
@wraps(fn)in decorators: Without it, every decorated function loses its__name__,__qualname__,__doc__,__annotations__, andinspect.signature(), breaking debugging,help(), and frameworks like FastAPI/pytest. - Calls
update_wrapperunder the hood: Preserves__wrapped__so callers can unwrap the decorator stack.
REPL Inspect
from functools import wraps
help(wraps)
Linked from
Related notes
- tuts/python3/stdlib_module/functools/update_wrapper Linked here; links to this page; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/functools/cache Linked here; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/cached_property Linked here; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/cmp_to_key Linked here; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/lru_cache Linked here; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/partial shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/partialmethod shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/reduce shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/singledispatch shared tags: #functools, #stdlib