Skip to main content

functools

Tools for working with functions and callables: caches, partial application, reduction, single-dispatch, and decorator helpers.

Source-of-record: Lib/functools.py, Modules/_functoolsmodule.c, functools docs.

Caching

FunctionReturns
@functools.cacheUnbounded lru_cache(maxsize=None).
@functools.lru_cache(maxsize=128, typed=False)Bounded LRU cache decorator.
@functools.cached_propertyCompute once, store on instance.

Cache info: .cache_info() returns CacheInfo(hits, misses, maxsize, currsize). .cache_clear() empties. .cache_parameters() returns the kwargs.

Reduction

functools.reduce(function, iterable, initializer=missing)

Folds left. initializer provides the seed; without it the first iterable element seeds.

Partial application

Class / functionEffect
functools.partial(func, /, *args, **kw)Pre-bind positional and keyword args.
functools.partialmethod(func, /, *args, **kw)Same, but as a descriptor for class bodies.

Attributes: .func, .args, .keywords.

Dispatch

APIRole
@functools.singledispatchGeneric function dispatched on first arg type.
fn.register(type)(impl)Register an implementation.
fn.dispatch(cls)Pick the impl for cls.
fn.registryMapping of type to impl.
@functools.singledispatchmethodSame, as a method.

Decorator helpers

HelperRole
functools.wraps(wrapped, ...)Copy metadata onto a wrapper.
functools.update_wrapper(wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)The underlying logic.
WRAPPER_ASSIGNMENTS(__module__, __name__, __qualname__, __annotations__, __doc__).
WRAPPER_UPDATES(__dict__,).

Ordering

HelperRole
@functools.total_orderingFill in the missing comparison methods given one of __lt__, __le__, __gt__, __ge__ and __eq__.
functools.cmp_to_key(cmp)Adapt a 3-way comparator for key=.

Reduce-time evaluation

functools.reduce and functools.partial are both implemented in C for speed; Python equivalents live in Lib/functools.py.

Gopy status

AreaState
cache, lru_cache, cached_propertyComplete.
partial, partialmethodComplete; C-fast paths in module/_functools.
singledispatchComplete.
wraps, update_wrapper, total_ordering, cmp_to_keyComplete.

Reference

  • CPython 3.14: functools.
  • Lib/functools.py, Modules/_functoolsmodule.c.
  • module/functools/, module/_functools/. gopy port.