On this page
  1. functools
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Writing Well-Behaved Decorators with @wraps
  7. 2. Type-Based Polymorphism with @singledispatch
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects
  11. Constants & Attributes

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

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes