1. Home
  2. Blog
  3. Software Development

Software Development

Python functools Explained: lru_cache, partial, reduce, wraps and More, Tested

Python functools is the standard library toolbox for working with functions: caching results, pre-filling arguments, folding lists, writing proper decorators and dispatching on type. Here is what each tool does, with output we ran on Python 3.13.

9 min read
Python functools explained: lru_cache, partial, reduce and wraps

Key takeaways

  • Python functools is built in; the most useful tools are lru_cache, partial, wraps and cached_property.
  • Caching a recursive Fibonacci cut fib(30) from 0.106 seconds to 0.137 milliseconds in our run.
  • Without @wraps, our decorated function reported its name as inner and lost its docstring.
  • Cached functions need hashable arguments: passing a list raised TypeError.

Sooner or later every Python developer writes a slow function that gets called with the same inputs, a decorator that breaks debugging, or a lambda whose only job is to fix one argument. The Python functools module solves all three with a few well-tested tools. You do not need to install anything; it ships with every Python version you are likely to use.

All examples here were run on Python 3.13.6 and the printed output is copied from that run. Timings depend on hardware, so focus on the ratios. Decorators come up a lot below, so if they are new to you, start with our Python decorators guide.

What is functools?

functools is a standard library module for higher-order functions: functions that take or return other functions. It groups tools into three families:

  • Caching: lru_cache, cache and cached_property remember results.
  • Building functions: partial, reduce and singledispatch create or combine behaviour.
  • Helpers for classes and decorators: wraps and total_ordering fill in boilerplate.

lru_cache and cache: memoize slow functions

lru_cache stores the result for each set of arguments. The next call with the same arguments returns the stored value instead of recomputing it. Recursive functions with overlapping sub-problems benefit the most:

from functools import lru_cache

def fib_plain(n):
    return n if n < 2 else fib_plain(n - 1) + fib_plain(n - 2)

@lru_cache(maxsize=None)
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)

fib(30)
print(fib.cache_info())
fib(30) plain 0.106s cached 0.137ms
CacheInfo(hits=28, misses=31, maxsize=None, currsize=31)

The plain version makes over a million calls for n = 30. The cached one computed each value from 0 to 30 once (31 misses) and served the rest from the cache (28 hits). That turned roughly a tenth of a second into well under a millisecond.

Since Python 3.9, @cache is a shorter spelling of @lru_cache(maxsize=None): an unbounded cache with slightly less overhead. Use cache_info() to check hit rates and cache_clear() to empty the cache, for example between tests.

How maxsize really works

LRU stands for “least recently used”. When a bounded cache is full, the entry that was used longest ago is evicted. We set maxsize=2 and called a counting function with the inputs 1, 2, 1, 3, 1, 2:

@lru_cache(maxsize=2)
def sq(x):
    global calls
    calls += 1
    return x * x

for x in [1, 2, 1, 3, 1, 2]:
    sq(x)
print(calls, sq.cache_info())
4 CacheInfo(hits=2, misses=4, maxsize=2, currsize=2)

Walk through it: 1 and 2 are misses. The second 1 is a hit. Then 3 is a miss and evicts 2, the least recently used. The third 1 is a hit, and the final 2 is a miss again because it was evicted. Choose maxsize from real usage; a cache that is too small keeps throwing away exactly what you need next.

Tip: only cache pure functions, whose result depends only on their arguments. Caching a function that reads the clock, a database or a file will return stale data.

partial: pre-fill arguments

partial creates a new callable with some arguments already fixed. It is clearer than a one-line lambda and easier to inspect:

from functools import partial

pow2 = partial(pow, exp=2)
print(pow2(9))                      # 81

int_bin = partial(int, base=2)
print(int_bin("1011"))              # 11
print(int_bin.func.__name__, int_bin.keywords)   # int {'base': 2}

The func, args and keywords attributes let you see what was fixed, which a lambda hides. Typical uses are callbacks for GUI buttons, pre-configured loggers and passing a configured function to map or a thread pool. If you prefer lambdas for one-off cases, our Python lambda functions guide compares the two styles.

reduce: fold a sequence into one value

reduce applies a two-argument function cumulatively from left to right. It moved from the built-ins into functools in Python 3:

from functools import reduce
import operator

print(reduce(operator.mul, [1, 2, 3, 4, 5]))   # 120
print(reduce(operator.add, [], 0))             # 0
reduce(operator.add, [])
TypeError: reduce() of empty iterable with no initial value

Always pass an initial value when the input could be empty. And check for a built-in first: sum, max, min, any, all and math.prod are clearer than reduce for the common cases. Keep reduce for genuinely custom folds, such as merging a list of dictionaries.

wraps: decorators that keep their identity

A decorator replaces a function with a wrapper. Without help, the wrapper’s name and docstring replace the original’s, which breaks logs, documentation and test reports. We decorated the same function with and without @wraps:

from functools import wraps

def nowrap(f):
    def inner(*a, **k):
        return f(*a, **k)
    return inner

def withwrap(f):
    @wraps(f)
    def inner(*a, **k):
        return f(*a, **k)
    return inner
no wraps: inner None
wraps: greet2 Say hello. greet2

With @wraps(f), the wrapper copies __name__, __doc__, __module__ and more, and adds __wrapped__ so tools can reach the original. Put it in every decorator you write; there is no downside.

cached_property: compute once per object

cached_property turns a method into an attribute that is computed on first access and then stored on the instance:

from functools import cached_property

class Report:
    def __init__(self, rows):
        self.rows, self.n = rows, 0
    @cached_property
    def total(self):
        self.n += 1
        return sum(self.rows)

r = Report([1, 2, 3])
r.total; r.total
print(r.n, r.total)    # 1 6

The property body ran once even though we read it three times. Because the value is stored in the instance dictionary, deleting it with del r.total forces a recompute. It suits expensive values that do not change during an object’s life, such as a parsed config. For more on classes, see our Python classes and objects guide.

singledispatch: one function, many types

singledispatch picks an implementation based on the type of the first argument, which replaces long isinstance chains:

from functools import singledispatch

@singledispatch
def fmt(x):
    return f"obj:{x}"

@fmt.register
def _(x: int):
    return f"int:{x:,}"

@fmt.register
def _(x: list):
    return "list:" + ",".join(map(fmt, x))

print(fmt(1234567), fmt([1, "a"]), fmt(2.5))
int:1,234,567 list:int:1,obj:a obj:2.5

Registration reads the type hint, so the code stays tidy. New types can be added from other modules without touching the original function. For methods, use singledispatchmethod. Type hints in general are covered in our Python type hints guide.

total_ordering: fewer comparison methods

Define __eq__ and one of __lt__, __le__, __gt__ or __ge__, and @total_ordering fills in the rest. In our test, a version class with only __eq__ and __lt__ answered Ver(1,2) >= Ver(1,1) with True and Ver(1,2) <= Ver(1,1) with False. The generated methods are a little slower than hand-written ones, so skip it in very hot code.

Pitfalls to avoid

  • Unhashable arguments. Cached functions build a key from the arguments. Calling a cached function with a list raised TypeError: unhashable type: 'list' in our run. Convert to a tuple first.
  • Caching methods. lru_cache on an instance method includes self in the key and keeps every instance alive as long as the cache does. Prefer cached_property or a module-level cached function.
  • Unbounded memory. @cache never evicts. For inputs from users or the network, set a maxsize.
  • Mutable results. A cached list or dict is shared by every caller. If one caller changes it, everyone sees the change.
  • Stale caches in tests. Call cache_clear() in a fixture so one test cannot leak results into another.

Python functools cheat sheet

Tool Use it to Since
lru_cache Memoize with a size limit 3.2
cache Memoize without a limit 3.9
cached_property Compute an attribute once per object 3.8
partial Fix some arguments of a function 2.5
reduce Fold a sequence into one value moved in 3.0
wraps Keep metadata in decorators 2.5
singledispatch Choose an implementation by type 3.4
total_ordering Generate comparison methods 2.7

Final thoughts

Python functools rewards a small investment. Add @wraps to every decorator, reach for lru_cache or cache when a pure function repeats work, and replace argument-fixing lambdas with partial. Our measurements showed the payoff clearly: one decorator line made a recursive function several hundred times faster. Pair these tools with Python generators and you will write shorter, faster, more readable code.

Frequently asked questions

What is the difference between lru_cache and cache?

cache is an unbounded cache, the same as lru_cache with maxsize set to None. lru_cache accepts a maxsize and evicts the least recently used entry when it is full.

Why does lru_cache raise TypeError: unhashable type?

The cache uses the arguments as a dictionary key, so they must be hashable. Lists, dicts and sets are not; convert them to tuples or frozensets before calling.

Why should I use functools.wraps in decorators?

Without it, the decorated function takes the wrapper’s name and loses its docstring, which confuses logs, help text and test reports. wraps copies that metadata across.

Is functools.partial better than a lambda?

For fixing arguments, usually yes. A partial object is clearer, can be pickled when its function can, and exposes func, args and keywords for inspection.

Is reduce still recommended in Python 3?

Use it sparingly. Built-ins such as sum, max, min, any, all and math.prod are clearer for common cases; keep reduce for custom folds and always give an initial value.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Levenshtein Distance: Formula, Worked Table and Python Code

Levenshtein distance explained: the edit operations, the dynamic programming table for kitten and sitting, Python code with two-row memory, normalised…

Read article →
Software Development

URL Encoding Explained: Spaces, Plus Signs and UTF-8

URL encoding explained with tested Python and JavaScript code: percent encoding, reserved characters, %20 vs plus, UTF-8 bytes, encodeURI vs…

Read article →
DevOps

Gitignore: Patterns, Negation and Fixing Tracked Files

A tested gitignore guide: pattern rules, leading and trailing slashes, negation with !, the ignored parent folder trap, git check-ignore…

Read article →
Software Testing

Acceptance Criteria: Given When Then Examples and Checklist

How to write acceptance criteria testers can run: rule-based and Given When Then formats, a worked discount code example turned…

Read article →
Software Testing

State Transition Testing: Diagram, Table and Example

State transition testing explained with a login lockout example: states, events, the diagram, the state table, valid and invalid transitions,…

Read article →
Databases & SQL

Second Highest Salary in SQL: 5 Tested Ways and the Tie Trap

Find the second highest salary in SQL five ways: MAX subquery, LIMIT OFFSET, DENSE_RANK, a correlated subquery and per department,…

Read article →
Databases & SQL

SQL ROW_NUMBER: Top N per Group, Dedupe and Pagination

SQL ROW_NUMBER explained with tested queries: PARTITION BY, top N per group, deleting duplicates, pagination, the tie trap and how…

Read article →
Software Development

JavaScript Set: Union, Intersection and Removing Duplicates

JavaScript Set explained with tested examples: add, has, delete, deduplicating arrays, the new union and intersection methods, equality rules and…

Read article →
Test Automation

Python Unittest: Assert Methods, setUp and Mocks With Examples

A practical Python unittest tutorial: TestCase, assert methods, setUp and tearDown, subTest, skips, expected failures and mock, with a test…

Read article →
Software Development

Python Map and Filter: Examples vs List Comprehensions

Python map and filter explained with tested examples: lazy map objects, multiple iterables, filter(None), chaining, and a timed comparison with…

Read article →
Artificial Intelligence

Jaccard Similarity: Formula, Python, MinHash

Jaccard similarity measures overlap between two sets as intersection over union. Work the formula, compute it in Python for words…

Read article →
Software Development

Unix Timestamp Explained: Seconds vs ms

A Unix timestamp counts seconds since 1 January 1970 UTC. Learn seconds vs milliseconds, converting in Python, JavaScript and SQL,…

Read article →
DevOps

Git Hooks: Pre-commit and Commit-msg Examples

Git hooks run scripts at key moments such as commit and push. See tested pre-commit, commit-msg and prepare-commit-msg hooks, sharing…

Read article →
Test Automation

API Testing in Python: Pytest + Requests Suite

Build an API testing suite in Python with pytest and requests: fixtures, status codes, headers, JSON schema validation, CRUD flows,…

Read article →
Software Testing

Test Design Techniques: 9 Methods + Examples

Test design techniques help you write fewer tests that catch more bugs. Learn 9 black-box, white-box and experience-based methods with…

Read article →
Databases & SQL

SQL Temporary Table: Create, Use and Drop It

SQL temporary tables store interim results for one session. Learn syntax for SQL Server, PostgreSQL, MySQL, Oracle and SQLite, session…

Read article →
Databases & SQL

SQL CROSS JOIN: Every Combination + Examples

SQL CROSS JOIN returns every combination of rows from two tables. See the row math, product variants, calendar grids that…

Read article →
Software Development

JavaScript Date: Format, Parse, Timezone Bugs

JavaScript Date explained with tested Node.js code: zero-based months, the date-only UTC parsing trap, toISOString, getTimezoneOffset, Intl formatting, date math…

Read article →
Software Development

Python Requests: GET, POST, Timeouts, Retries

Python requests explained with code tested against a local API: GET with params, POST json vs data, headers and auth,…

Read article →
Artificial Intelligence

TF-IDF Explained: Formula and Worked Example

TF-IDF scores a word by how often it appears in a document and how rare it is across all documents….

Read article →
DevOps

Git Tag: Create, Push and Delete Release Tags

Git tag explained with tested commands: annotated vs lightweight tags, listing and sorting, pushing with follow-tags, deleting local and remote…

Read article →
Test Automation

Pytest Coverage: pytest-cov and Branch Gaps

Measure pytest coverage with pytest-cov: term-missing reports, branch coverage, HTML reports, pyproject settings and a fail-under gate for CI, with…

Read article →
Software Testing

Error Guessing in Testing: Checklist + Demo

Error guessing uses tester experience to predict where code breaks. Get a ready checklist of risky inputs, a step by…

Read article →
Databases & SQL

SQL LAG and LEAD: Compare Rows, 5 Examples

SQL LAG and LEAD read values from the previous or next row without a self join. Five tested examples: change,…

Read article →
Databases & SQL

SQL STRING_AGG: Combine Rows Into One String

SQL STRING_AGG joins values from many rows into one string per group. See syntax for PostgreSQL, SQL Server, MySQL GROUP_CONCAT,…

Read article →
Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →
Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive vs negative testing explained with a real signup form: 6 positive and 18 negative test cases run in pytest,…

Read article →
Artificial Intelligence

Cosine Similarity Explained: Formula, Worked Example and Python Code

Cosine similarity explained simply: the formula, a worked example by hand, pure Python and NumPy code, cosine vs Euclidean distance…

Read article →
DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step (rebase -i, reset, merge)

Git squash commits explained with 4 tested methods: interactive rebase, reset –soft, merge –squash and fixup with autosquash. Before-and-after logs,…

Read article →
Test Automation

pytest parametrize Explained: 7 Patterns with Tested Examples

pytest parametrize explained with 7 tested patterns: basic cases, readable ids, stacked decorators, pytest.param with xfail and skip, indirect fixtures…

Read article →
Software Testing

Retesting vs Regression Testing: 8 Key Differences with a Real Bug Fix Example

Retesting vs regression testing explained with a real bug fix run in pytest: retesting confirmed the fix, the regression run…

Read article →
Artificial Intelligence

RAG Chunking Strategies Explained: Fixed, Overlap, Sentence, Recursive and Headings, Measured

RAG chunking strategies compared on one document with tiktoken 0.14: fixed-size, overlap, sentence packing, recursive splitting and heading-based chunks, measuring…

Read article →
DevOps

Git Stash Explained: Save, Apply, Pop and Untracked Files, Tested

Git stash explained with commands we ran on Git 2.56: push with a message, untracked files, list and show, apply…

Read article →
Test Automation

Test Doubles Explained: Dummy, Stub, Spy, Mock and Fake, with Tested Python Code

Test doubles explained with one Python example run in pytest 9.2: dummy, stub, spy, mock and fake, when to use…

Read article →