A function that fetches a train's running status takes 2 seconds, because it calls a slow website. Your app calls it 50 times a minute for the same 10 trains. The answer barely changes, yet you wait 100 seconds every minute. One line, @lru_cache, makes Python remember each answer, so repeat calls come back instantly. That line comes from Python functools, a standard library module of tools that work on functions.
functools sits naturally beside itertools: itertools helps with iterators, functools helps with functions. This lesson covers the tools you'll actually meet: partial to preset arguments, reduce to combine values, lru_cache and cache to remember results, cmp_to_key for unusual sorting, and a few helpers for classes and decorators.
What you need first: lambda, map, filter and sorted, recursion in Python and variable scope and closures.
Key terms
- Higher-order function: a function that takes a function as input or returns one. Everything in functools is one.
- Partial function: a new function made from an existing one with some arguments already filled in.
- Memoisation (caching): storing a function's results so the same inputs don't have to be worked out again.
- Decorator: a function that wraps another function to add behaviour, written with
@nameabove adef. - Pure function: a function whose result depends only on its inputs and which changes nothing else. Only pure functions are safe to cache.
partial: preset some arguments
partial(func, *args, **kwargs) makes a new function with some arguments already fixed. Say you often calculate prices with 18% GST, and sometimes 5%:
from functools import partial
def price_with_tax(price, rate):
return round(price * (1 + rate), 2)
with_gst_18 = partial(price_with_tax, rate=0.18)
with_gst_5 = partial(price_with_tax, rate=0.05)
print(with_gst_18(1000))
print(with_gst_5(1000))
1180.0
1050.0
It's the same as writing a small def or lambda, but shorter, and the result keeps a record of what it wraps:
from functools import partial
def price_with_tax(price, rate):
return round(price * (1 + rate), 2)
with_gst_18 = partial(price_with_tax, rate=0.18)
print(with_gst_18.func.__name__, with_gst_18.keywords)
price_with_tax {'rate': 0.18}
partial is handy wherever a tool wants a function with fewer arguments than yours has. int with base=2 turns binary strings into numbers, and map needs a one-argument function:
from functools import partial
from_binary = partial(int, base=2)
print(list(map(from_binary, ["101", "1111", "100000"])))
[5, 15, 32]
reduce: combine a sequence into one value
reduce(func, iterable, initial) applies a two-argument function across the items, carrying the result along. For [a, b, c, d] it works out func(func(func(a, b), c), d):
from functools import reduce
numbers = [2, 3, 4, 5]
print(reduce(lambda total, n: total * n, numbers))
120
Working through it: 2 × 3 = 6, then 6 × 4 = 24, then 24 × 5 = 120.
Give an initial value to start from, which also makes reduce safe on an empty list:
from functools import reduce
print(reduce(lambda a, b: a + b, [], 0))
carts = [{"pen": 2}, {"pen": 1, "book": 1}, {"book": 3}]
def merge(total, cart):
for item, qty in cart.items():
total[item] = total.get(item, 0) + qty
return total
print(reduce(merge, carts, {}))
0
{'pen': 3, 'book': 4}
Without the initial value, reduce on an empty list raises TypeError: reduce() of empty iterable with no initial value.
Our honest advice: reach for sum, max, min, math.prod, "".join or a plain loop first. They're clearer. reduce earns its place when you're combining things in a custom way, like merging dictionaries, and you'll see it often in other people's code.
lru_cache: remember results
Here's a slow function. It pretends to call a website by sleeping for half a second:
import time
from functools import lru_cache
@lru_cache(maxsize=128)
def train_status(train_number):
time.sleep(0.5) # pretend this is a slow web request
return f"Train {train_number}: on time"
start = time.perf_counter()
for number in [12951, 12951, 12002, 12951, 12002]:
train_status(number)
elapsed = time.perf_counter() - start
print(f"5 calls took about {elapsed:.1f} s")
print(train_status.cache_info())
5 calls took about 1.0 s
CacheInfo(hits=3, misses=2, maxsize=128, currsize=2)
Five calls but only two different trains, so only two slow calls happened (misses); the other three came straight from the cache (hits). Without the cache it would take about 2.5 seconds.
How it works: the decorator keeps a dictionary from the arguments to the result. Before running the function, it checks whether it has seen those arguments. LRU means "least recently used": when the cache holds maxsize results, the one used longest ago is thrown out to make room.
| Setting | Means |
|---|---|
@lru_cache(maxsize=128) | Keep the 128 most recently used results (128 is the default) |
@lru_cache(maxsize=None) | No limit: keep everything |
@cache | Same as lru_cache(maxsize=None); Python 3.9 and newer |
func.cache_info() | Hits, misses and current size |
func.cache_clear() | Empty the cache |
Caching recursive functions
Caching turns slow recursive code into fast code, as the recursion lesson showed with Fibonacci:
from functools import cache
@cache
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(30))
print(fib.cache_info())
832040
CacheInfo(hits=28, misses=31, maxsize=None, currsize=31)
31 real calculations (for 0 to 30) instead of more than 26 lakh calls without the cache.
When not to cache
- Functions with side effects: a function that sends an email or saves to a database must run every time. Caching would silently skip the work.
- Results that change over time: "current time" or "latest price" would freeze at the first value. (For the train example, a real app would clear the cache every few minutes.)
- Unhashable arguments: arguments are used as dictionary keys, so lists and dictionaries can't be passed. You get
TypeError: unhashable type: 'list'. Pass tuples instead. - Huge, rarely repeated inputs, where the cache just uses memory.
cmp_to_key: sorting with a comparison function
A key function turns each item into a value to compare. Some orderings can't be described that way and need you to compare two items directly. The classic interview problem: arrange numbers to form the largest possible number. 9, 5, 34, 3 and 30 should give 9534330.
Compare two numbers a and b by checking which joined string is bigger, a + b or b + a:
from functools import cmp_to_key
def compare(a, b):
if a + b > b + a:
return -1 # a goes first
if a + b < b + a:
return 1 # b goes first
return 0
numbers = ["3", "30", "34", "5", "9"]
ordered = sorted(numbers, key=cmp_to_key(compare))
print("".join(ordered))
9534330
A comparison function returns a negative number if a should come first, positive if b should, and 0 if they're equal. cmp_to_key converts it into a key that sorted accepts. You'll rarely need it, but when you do, nothing else works as neatly.
total_ordering: fewer comparison methods
To make objects of your own class sortable and comparable with <, >, <= and >=, you'd normally write four methods. @total_ordering fills in the rest if you write __eq__ and one of them:
from functools import total_ordering
@total_ordering
class Version:
def __init__(self, text):
self.parts = tuple(int(p) for p in text.split("."))
self.text = text
def __eq__(self, other):
return self.parts == other.parts
def __lt__(self, other):
return self.parts < other.parts
def __repr__(self):
return self.text
versions = [Version("3.12.1"), Version("3.9.18"), Version("3.13.0")]
print(sorted(versions))
print(Version("3.10.0") >= Version("3.9.0"))
[3.9.18, 3.12.1, 3.13.0]
True
As strings, "3.9" would sort after "3.12"; as tuples of numbers, 9 < 12, which is correct. A dataclass with order=True is another way to get all the comparisons.
wraps: keep a function's name in decorators
When you write a decorator, the wrapped function loses its own name and docstring, which makes debugging confusing. functools.wraps copies them across:
from functools import wraps
def shout(func):
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs).upper()
return wrapper
@shout
def greet(name):
"""Return a greeting."""
return f"hello, {name}"
print(greet("ahana"))
print(greet.__name__, "-", greet.__doc__)
HELLO, AHANA
greet - Return a greeting.
Without @wraps(func), the last line would print wrapper - None. Decorators get a lesson of their own later in this module; for now, remember that every decorator you write should use @wraps.
cached_property: work out an attribute once
@cached_property works like @property, but runs the method only the first time and then stores the result on the object:
from functools import cached_property
class Report:
def __init__(self, sales):
self.sales = sales
@cached_property
def total(self):
print(" (calculating total)")
return sum(self.sales)
r = Report([1200, 950, 1430])
print(r.total)
print(r.total)
(calculating total)
3580
3580
The total was worked out once. If self.sales changes later, the cached total won't update; use it only for values that stay fixed for the object's life.
Quick reference
| Tool | Use it to |
|---|---|
partial(func, ...) | Make a version of a function with some arguments preset |
reduce(func, items, initial) | Combine items into one value in a custom way |
@lru_cache(maxsize=n) | Remember recent results of a pure function |
@cache | Remember all results (Python 3.9+) |
cmp_to_key(cmp) | Sort with a two-item comparison function |
@total_ordering | Get all comparison operators from __eq__ and one more |
@wraps(func) | Keep the name and docstring in a decorator |
@cached_property | Calculate an attribute once per object |
Where functools is used
- Web apps and APIs:
lru_cacheon functions that read settings or call slow services. - Dynamic programming:
@cacheon recursive solutions is the quickest way to pass many interview problems. - Data pipelines:
partialto preset options before passing functions tomapor pandas'apply. - Libraries: almost every decorator in popular libraries uses
wraps.
Common mistakes
- Caching a function with side effects or one whose answer changes over time.
- Passing lists or dictionaries to a cached function, which raises
TypeError: unhashable type. reduceon a possibly empty list with no initial value.- Using
reducewheresumormaxwould do, which makes code harder to read. - Writing a decorator without
@wraps, which hides the real function's name in errors and logs.
Practice
- Use
partialto makesquareandcubefrom the built-inpow.
Show the answer
pow(base, exp) takes the exponent second, so preset it with a keyword:
from functools import partial
square = partial(pow, exp=2)
cube = partial(pow, exp=3)
print(square(7), cube(3))
49 27
- Use
reduceto find the longest word in["chai", "samosa", "jalebi", "vadapav"].
Show the answer
Keep whichever of the two is longer at each step:
from functools import reduce
words = ["chai", "samosa", "jalebi", "vadapav"]
print(reduce(lambda a, b: a if len(a) >= len(b) else b, words))
vadapav
max(words, key=len) is the clearer way to write this in real code.
- Add caching to this function and print the cache statistics after the calls.
def slow_square(n):
return n * n
for n in [4, 5, 4, 4, 6]:
slow_square(n)
Show the answer
from functools import lru_cache
@lru_cache(maxsize=None)
def slow_square(n):
return n * n
for n in [4, 5, 4, 4, 6]:
slow_square(n)
print(slow_square.cache_info())
CacheInfo(hits=2, misses=3, maxsize=None, currsize=3)
4, 5 and 6 are new (3 misses); the second and third 4 are hits.
- Why is caching this function a bad idea?
from functools import cache
import datetime
@cache
def greeting():
hour = datetime.datetime.now().hour
return "Good morning" if hour < 12 else "Good evening"
Show the answer
Its result depends on the current time, not only on its arguments. After the first call, it would keep returning the same greeting for the rest of the program's life, even hours later.
- Use
@cacheto count the ways to climb n stairs taking 1 or 2 steps at a time. Print the answer for 10 and 50 stairs.
Show the answer
The last step was either 1 or 2, so ways(n) = ways(n − 1) + ways(n − 2), with ways(0) = ways(1) = 1:
from functools import cache
@cache
def ways(n):
if n <= 1:
return 1
return ways(n - 1) + ways(n - 2)
print(ways(10), ways(50))
89 20365011074
Without @cache, ways(50) would take billions of calls.
Interview questions
What does functools.lru_cache do and when should you avoid it?
It memoises a function: results are stored in a dictionary keyed by the arguments, so repeated calls return immediately, and the least recently used entries are discarded once maxsize is reached. Avoid it for functions with side effects, results that depend on time or external state, or unhashable arguments.
What is the difference between partial and a lambda?
Both can preset arguments. partial is clearer for that one job, can be inspected (.func, .args, .keywords) and can be pickled more easily. A lambda can do any one-line transformation, not just preset arguments.
Why use functools.wraps in a decorator?
A decorator replaces the original function with a wrapper, which has its own __name__ and __doc__. wraps copies the original's name, docstring and other metadata onto the wrapper, so tracebacks, logs, documentation tools and help() still show the real function.
Key takeaways
partialpresets arguments to make a simpler version of a function.reducecombines items with a two-argument function; give an initial value, and prefersum/maxwhen they fit.@lru_cacheand@cacheremember results of pure functions with hashable arguments; check them withcache_info().cmp_to_keyadapts a two-item comparison forsorted;@total_orderingfills in comparison methods.- Use
@wrapsin every decorator, and@cached_propertyfor values worked out once per object.
Frequently asked questions
What is the difference between cache and lru_cache?
@cache (Python 3.9+) is @lru_cache(maxsize=None): it keeps every result and never discards any. @lru_cache(maxsize=n) keeps only the n most recently used results, which limits memory.
Is reduce a built-in function in Python 3?
No. It was a built-in in Python 2 but moved to functools in Python 3. Import it with from functools import reduce.
Does lru_cache work on methods inside a class?
It works, but the cache holds a reference to self, which can keep objects alive longer than expected. For per-object values, @cached_property is usually the better choice.
What to learn next
- Revise the other half of this pair in the Python itertools module.
- See memoisation from the start in recursion in Python.
- Check how fast cached solutions are with Big-O notation.