Skip to content

Archive

Functools

3 articles
Python 04 Sep 2026 9 min read

Use functools.singledispatch for Type-Based Extension Points in Python

A function often starts with one input type and later grows branches for several related types. The first version may be straightforward: def render(value): if isinstance(value, str): ... elif isinstance(value, list): ... elif isinstance(value, dict): ... As the number of supported types grows, this function becomes the place where every extension must be added. The branches mix dispatch logic with the behavior for each type, and independently maintained modules cannot add support without editing the central function.

Python 02 Sep 2026 7 min read

Single Dispatch in Python: Extensible Type-Based Behavior

A function that accepts several kinds of input often begins with a few isinstance() checks. That approach is straightforward when the cases are small and local. As the number of supported types grows, however, one function can become a long decision tree that mixes unrelated implementations. Python’s functools.singledispatch offers another design. It turns one function into a generic function whose implementation is selected from the runtime type of its first argument. Type-specific behavior can then be registered separately while callers keep using one public function.

Python 02 Sep 2026 4 min read

Cache Pure Work in Python with functools.cache and lru_cache

Caching can turn repeated expensive work into a dictionary lookup, but it can also return stale data or grow memory without bound. Python’s functools module provides two convenient memoization decorators: lru_cache and cache. functools.cache has been available since Python 3.9. It is effectively an unbounded memoization cache. lru_cache adds a configurable size limit and eviction behavior. Cache functions, not arbitrary side effects Memoization works best when a function behaves like a pure function: the result depends only on its arguments.