functools.update_wrapper
Prev: functools.total_ordering | Up: functools | Next: functools.wraps
Rel: functools.cache, functools.cached_property, functools.cmp_to_key, functools.lru_cache
Ref: docs.python.org — functools.update_wrapper
Tags: #public #python3 #stdlib #functools
Import
import functools
from functools import update_wrapper
Signature & Overview
functools.update_wrapper(wrapper, wrapped, assigned=('__module__', '__name__', '__qualname__', '__doc__', '__annotate__', '__type_params__'), updated=('__dict__',))
Update a wrapper function to look like the wrapped function wrapper is the function to be updated wrapped is the original function
Usage
from functools import update_wrapper
def make_logged(fn):
def wrapper(*args, **kwargs):
return fn(*args, **kwargs)
return update_wrapper(wrapper, fn)
def greet(name: str) -> str:
"""Say hello."""
return f"hi {name}"
wrapped = make_logged(greet)
assert wrapped.__name__ == "greet" and wrapped.__doc__ == "Say hello."
assert wrapped.__wrapped__ is greet
Gotchas
- Usually called via
@wraps(fn): Use@wraps(fn)inside decorator functions andupdate_wrapper(wrapper, fn)directly when building callable wrapper objects (like classes with__call__). - Sets
__wrapped__: Enablesinspect.signature()andinspect.unwrap()to see through the wrapper to the original function.
REPL Inspect
from functools import update_wrapper
help(update_wrapper)
Linked from
Related notes
- tuts/python3/stdlib_module/functools/total_ordering Linked here; links to this page; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/wraps 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