On this page
functools
Prev: ftplib | Up: stdlib_module | Next: gc
Rel: itertools, operator
Ref: docs.python.org — functools
Tags: #public #python3 #stdlib
Import
import functools
Overview
Higher-order functions and decorators for caching (lru_cache, cache, cached_property), partial application (partial), decorator metadata preservation (wraps), single-dispatch polymorphism (singledispatch), and ordering (total_ordering).
Quick Start
from functools import lru_cache, partial
@lru_cache(maxsize=128)
def fib(n: int) -> int:
return n if n < 2 else fib(n - 1) + fib(n - 2)
assert fib(10) == 55
base2 = partial(int, base=2)
assert base2("1010") == 10
Implementation Walkthrough
1. Writing Well-Behaved Decorators with @wraps
Always decorate inner wrapper functions with @wraps(fn) so __name__, __doc__, __annotations__, and inspect.signature() are preserved:
from functools import wraps
import time
def timed(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
start = time.perf_counter()
try:
return fn(*args, **kwargs)
finally:
elapsed_ms = (time.perf_counter() - start) * 1000
# log or record elapsed_ms
return wrapper
2. Type-Based Polymorphism with @singledispatch
from functools import singledispatch
@singledispatch
def summarize(value: object) -> str:
return repr(value)
@summarize.register
def _(value: list) -> str:
return f"list[{len(value)}]"
@summarize.register
def _(value: dict) -> str:
return f"dict[{len(value)} keys]"
assert summarize([1, 2, 3]) == "list[3]"
Gotchas & Boundaries
- Never use
@lru_cacheon instance methods carelessly: The cache holds strong references toself, which can leak instances forever; use@cached_propertyfor per-instance caching or cache on a standalone helper. - Cached arguments must be hashable: Passing a
listordictto an@lru_cachefunction raisesTypeError: unhashable type. @cacheis unbounded: Prefer@lru_cache(maxsize=...)on long-running services so memory cannot grow without limit.- Avoid
reduce()when a built-in exists:sum(),any(),all(),math.prod(), or an explicitforloop is almost always clearer.
Common Functions
- functools.cache() —
cache(user_function, /)— Simple lightweight unbounded cache. Sometimes called "memoize". - functools.cmp_to_key() —
cmp_to_key(mycmp)— Convert a cmp= function into a key= function. - functools.lru_cache() —
lru_cache(maxsize=128, typed=False)— Least-recently-used cache decorator. - functools.reduce() —
reduce(...)— Apply a function of two arguments cumulatively to the items of an iterable, from left to right. - functools.singledispatch() —
singledispatch(func)— Single-dispatch generic function decorator. - functools.total_ordering() —
total_ordering(cls)— Class decorator that fills in missing ordering methods - functools.update_wrapper() —
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 - functools.wraps() —
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
Classes & Objects
- functools.cached_property —
functools.cached_propertyclass. - functools.partial — Create a new function with partial application of the given arguments and keywords.
- functools.partialmethod — Method descriptor with partial application of the given arguments and keywords.
- functools.singledispatchmethod — Single-dispatch generic method descriptor. (Methods:
.register())
Constants & Attributes
functools.Placeholder(_PlaceholderType) =Placeholderfunctools.WRAPPER_ASSIGNMENTS(tuple) =('__module__', '__name__', '__qualname__', '__doc__', '__...functools.WRAPPER_UPDATES(tuple) =('__dict__',)
Linked from
- tuts/python3/python decorators
- tuts/python3/python functions
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/ftplib
- tuts/python3/stdlib_module/functools/cache
- tuts/python3/stdlib_module/functools/cached_property
- tuts/python3/stdlib_module/functools/cmp_to_key
- tuts/python3/stdlib_module/functools/lru_cache
- tuts/python3/stdlib_module/functools/partial
- tuts/python3/stdlib_module/functools/partialmethod
- tuts/python3/stdlib_module/functools/reduce
- tuts/python3/stdlib_module/functools/singledispatch
- tuts/python3/stdlib_module/functools/singledispatchmethod
- tuts/python3/stdlib_module/functools/total_ordering
- tuts/python3/stdlib_module/functools/update_wrapper
- tuts/python3/stdlib_module/functools/wraps
- tuts/python3/stdlib_module/gc
- tuts/python3/stdlib_module/itertools
- tuts/python3/stdlib_module/operator
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/tutorials/advanced_python_internals/decorators_and_closures
- tuts/python3/tutorials/core_fundamentals/functions
Related notes
- tuts/python3/stdlib_module/ftplib Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/functools/cache Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/functools/cached_property Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/functools/cmp_to_key Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/functools/lru_cache Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/functools/partial Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/functools/partialmethod Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/functools/reduce Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/functools/singledispatch Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/functools/singledispatchmethod Linked here; links to this page; shared tags: #stdlib