Skip to content

Lesson 25 of 52Pythonic Python

functools, itertools and operator

Cache safely, dispatch on type, build fast key functions, and solve batching, windowing and grouping jobs with lazy itertools pipelines.

19 min read0/4 questions

A ticket lands on your board: "The nightly job sends 40,000 user IDs to the billing API one at a time and takes three hours. The API accepts 100 per request." Another says the report endpoint recomputes the same totals on every page load. A third says the daily summary shows some dates twice. All three are one import away from a fix, and all three have a classic bug waiting if you use that import carelessly. You have already met the basics: count, chain, groupby and batched in Iterators and Generators, cache and wraps in Decorators, reduce and partial in Higher-Order Functions. This lesson goes further: how these tools behave underneath, the traps that show up in code review, and the patterns seniors reach for without thinking.

Iterators are single-use, and that matters here

Almost everything in itertools takes an iterable and returns an iterator: a lazy object that hands out one value at a time and remembers its position. Nothing is computed until something pulls values, and once a value is pulled it is gone. That laziness is why you can process a 20 GB log file in constant memory. It is also the source of the most common bug with these tools.

Python
def read_amounts(): for line in ["12", "30", "8"]: # imagine a huge file yield int(line) amounts = read_amounts()print("total:", sum(amounts))print("max:", max(amounts, default="nothing left")) # Fix 1: materialise once if it fits in memoryamounts = list(read_amounts())print(sum(amounts), max(amounts)) # Fix 2: compute both in one pass if it does nottotal, biggest = 0, Nonefor a in read_amounts(): total += a biggest = a if biggest is None else max(biggest, a)print(total, biggest)
Output
Press Run (⌘ Enter) to see what happens.

The second call got an empty iterator and no error. In real code the symptom is a report where the second column is always zero, or a validation step that "passes" because it consumed the data before the writer saw it. When a function receives an iterable and needs to walk it twice, either call list() on it first or document that it must be a re-iterable collection.

itertools.tee(it, n) looks like the answer, since it splits one iterator into n independent ones. But it buffers every value that one copy has seen and another has not. If one consumer runs to the end before the other starts, tee stores the whole stream, and you would have been better off with a list. Use it only when the copies advance roughly together.

Predict the outputPython

What does this print?

nums = (n * n for n in range(4))
big = [n for n in nums if n > 1]
print(len(big), len(list(nums)))
Need a nudge? Hints walk you through it.

itertools by job

Learn itertools by the job you need done, not alphabetically. These are the jobs that come up at work.

Batching: batched

Back to the billing ticket. itertools.batched(it, n) (3.12) yields tuples of up to n items. Since 3.13 you can pass strict=True to raise ValueError if the last batch is short, which is useful when a short batch means corrupt input, such as records that must come in pairs.

Python
from itertools import batched user_ids = range(1, 251) # 250 IDs from the database def call_billing_api(batch): return len(batch) # pretend HTTP call calls = 0for batch in batched(user_ids, 100): call_billing_api(batch) calls += 1 print(f"request {calls}: {batch[0]}..{batch[-1]} ({len(batch)} ids)") try: list(batched([1, 2, 3, 4, 5], 2, strict=True))except ValueError as e: print("ValueError:", e)
Output
Press Run (⌘ Enter) to see what happens.

Three hours becomes a couple of minutes, and memory stays flat because batched pulls only 100 IDs at a time from the source.

Windows: pairwise and a sliding window

pairwise gives overlapping pairs, which covers "change since yesterday". For a wider window, such as a 3-day moving average, the docs' recipe uses a deque with maxlen, which drops the oldest item automatically.

Python
from collections import dequefrom itertools import islice, pairwise def sliding_window(iterable, n): it = iter(iterable) window = deque(islice(it, n - 1), maxlen=n) for x in it: window.append(x) yield tuple(window) daily_signups = [120, 135, 90, 160, 150, 170]print([b - a for a, b in pairwise(daily_signups)])print([round(sum(w) / 3, 1) for w in sliding_window(daily_signups, 3)])
Output
Press Run (⌘ Enter) to see what happens.

Running totals: accumulate

accumulate yields every intermediate result of a fold, not just the last one like reduce. Pass any two-argument function: max gives a running maximum (a "high water mark"), and initial= adds a starting value.

Python
from itertools import accumulateimport operator deposits = [100, -30, 50, -200, 80]print(list(accumulate(deposits))) # running balanceprint(list(accumulate(deposits, initial=1000))) # starting balanceprint(list(accumulate([5, 3, 8, 1, 9], max))) # high water markprint(list(accumulate([1, 2, 3, 4], operator.mul))) # running product
Output
Press Run (⌘ Enter) to see what happens.

Cutting streams: islice, takewhile, dropwhile, compress

islice(it, start, stop) slices an iterator without materialising it. takewhile(pred, it) yields while the condition holds and stops at the first failure, even if later items would pass. dropwhile is the mirror: it skips until the first failure, then yields everything. That makes them perfect for sorted or time-ordered data, like skipping a log's startup noise. compress(data, selectors) keeps items whose matching selector is truthy.

Combining: chain.from_iterable and zip_longest

chain.from_iterable(list_of_lists) flattens one level lazily, which is the right tool for "concatenate the pages of an API response". Plain zip stops at the shortest input and silently drops the rest; zip_longest pads with a fillvalue. Since 3.10 you can also write zip(a, b, strict=True) to raise if the lengths differ, which is usually what you actually want when two lists must line up.

Python
from itertools import chain, zip_longest, takewhile, dropwhile, compress, starmap pages = [[1, 2], [3], [4, 5, 6]]print(list(chain.from_iterable(pages))) names = ["ada", "sam", "lee"]scores = [91, 78]print(list(zip(names, scores))) # lee silently lostprint(list(zip_longest(names, scores, fillvalue=None))) log = ["boot", "boot", "ready", "GET /", "boot", "GET /a"]print(list(dropwhile(lambda l: l != "ready", log)))print(list(takewhile(lambda l: l == "boot", log))) print(list(compress(names, [True, False, True])))print(list(starmap(pow, [(2, 10), (3, 3)]))) # f(*args) per tuple
Output
Press Run (⌘ Enter) to see what happens.

Combinatorics: sizes grow fast

product, permutations and combinations are lazy, which is good, because their output sizes explode. 20 items have 190 pairs, but 20 items have 2.4 quintillion orderings. Before you loop over one, compute its size with math.comb(n, k) or math.perm(n, k). If the number has more than about eight digits, you need a smarter algorithm, not a faster loop. In interviews, saying this out loud before writing a brute-force search shows exactly the judgement interviewers look for.

groupby groups runs, not keys

Now the "dates show up twice" ticket. groupby walks the input once and starts a new group every time the key changes. It does not collect equal keys from across the input. That makes it O(n) and lazy, but it means unsorted input produces repeated keys.

groupby on unsorted log dates
10-21
0
10-21
1
10-22
2
10-21
3
10-22
4
group = 10-21groups_so_far = 1

First run: two lines for 10-21. The key has not changed yet, so they form one group.

1/4
Python
from itertools import groupbyfrom operator import itemgetter lines = [ ("2026-10-21", "GET /"), ("2026-10-21", "POST /pay"), ("2026-10-22", "GET /"), ("2026-10-21", "GET /late"),] print([day for day, _ in groupby(lines, key=itemgetter(0))]) # bug: duplicate lines.sort(key=itemgetter(0))for day, group in groupby(lines, key=itemgetter(0)): print(day, len(list(group))) # Each group is a view on the shared iterator: save it before moving onsaved = {day: list(g) for day, g in groupby(lines, key=itemgetter(0))}print(saved["2026-10-22"])
Output
Press Run (⌘ Enter) to see what happens.

There is a second, subtler trap. Each group shares the underlying iterator with groupby itself, so once you advance to the next key, the previous group is empty. list(groupby(...)) gives you keys paired with groups that are already exhausted. Convert each group to a list inside the loop.

When the data is not already sorted and you do not need streaming, a defaultdict(list) is often clearer and avoids the O(n log n) sort. Use groupby when the input is naturally ordered (log files, time series, database results with ORDER BY) and you want constant memory.

Quick check
A query returns rows ordered by created_at. You call groupby(rows, key=lambda r: r.customer_id). What happens?
Need a nudge? A hint rules out a wrong answer.

operator: key functions without lambdas

operator.itemgetter, attrgetter and methodcaller build small callables that do one lookup. They read clearly, they are implemented in C so they are a little faster than an equivalent lambda, and unlike a lambda they can be pickled, which matters when you pass a key function to multiprocessing or store it in a task queue.

Python
from dataclasses import dataclassfrom operator import itemgetter, attrgetter, methodcallerimport pickle rows = [("lee", 78, "UK"), ("ada", 91, "FR"), ("sam", 78, "DE")]print(sorted(rows, key=itemgetter(1, 0))) # by score, then name @dataclassclass User: name: str team: str users = [User("Sam", "core"), User("Ada", "api"), User("Lee", "core")]print([u.name for u in sorted(users, key=attrgetter("team", "name"))]) print(list(map(methodcaller("upper"), ["a", "b"]))) pickle.dumps(itemgetter(1)) # finetry: pickle.dumps(lambda r: r[1])except Exception as e: print("lambda:", type(e).__name__)
Output
Press Run (⌘ Enter) to see what happens.

itemgetter(1, 0) returns a tuple, so you get multi-key sorts for free. attrgetter("address.city") follows dotted paths. The operator module also exposes every operator as a function (operator.add, operator.mul), which is what you pass to reduce and accumulate instead of lambda a, b: a + b.

Caching in depth

You know @cache and @lru_cache(maxsize=...) from Decorators. Here is what they do underneath and where they bite.

Each decorated function owns a dict. The key is built from the positional and keyword arguments, so they must all be hashable. With maxsize set, a doubly linked list tracks recency, and each hit moves its entry to the front; a miss beyond maxsize evicts the least recently used entry. cache_info() reports hits, misses and size, and cache_clear() empties it. Note that f(a=1, b=2) and f(b=2, a=1) may be cached as separate entries, so call cached functions consistently.

The cache structure is thread-safe, but the function is not locked. Two threads that miss at the same moment will both run the function. For an expensive call where that matters, you need your own lock.

The method trap

Putting @lru_cache on a method is one of the most common memory leaks in Python services. The cache lives on the function, which lives on the class, which lives forever. self is part of every key, so the cache holds a strong reference to every instance that was ever called.

lru_cache on a method keeps instances alive
NamesObjects in memoryreportReportrows=[...50 MB...]Report.total cache{(r1,): 4210}

report.total() is called once. The cache key is (self,), so the cache now points at the instance.

1/3
Python
import gcimport weakreffrom functools import lru_cache, cached_property class LeakyReport: def __init__(self, rows): self.rows = rows @lru_cache(maxsize=None) def total(self): return sum(self.rows) r = LeakyReport([1, 2, 3])r.total()ref = weakref.ref(r)del rgc.collect()print("leaky instance still alive:", ref() is not None) class Report: def __init__(self, rows): self.rows = rows @cached_property def total(self): print(" computing") return sum(self.rows) r = Report([1, 2, 3])print(r.total, r.total) # computed once, then read from r.__dict__del r.total # invalidateprint(r.total)ref = weakref.ref(r)del rgc.collect()print("cached_property instance alive:", ref() is not None)
Output
Press Run (⌘ Enter) to see what happens.

The fixes, in order of preference:

  • functools.cached_property when the value belongs to one instance. It stores the result in the instance's own __dict__, so it dies with the instance. Clear it with del obj.attr.
  • A module-level cached function keyed on plain data (compute_total(tuple(rows)) or an ID), not on self.
  • A per-instance cache built in __init__, such as self.total = lru_cache()(self._total), when you truly need per-instance LRU behaviour.

cached_property has two limits. It needs an instance __dict__, so it does not work on classes with __slots__ (including @dataclass(slots=True)) and raises TypeError on first access. And since 3.12 it has no lock: two threads can both compute the value the first time. Before 3.12 it had a lock that was shared across all instances and caused contention, so it was removed.

Quick check
A FastAPI service creates a new PriceCalculator per request and calls calc.quote(sku), decorated with @lru_cache(maxsize=None). Memory grows steadily. Why?
Need a nudge? A hint rules out a wrong answer.

singledispatch: one function, many types

When a function needs different behaviour per argument type, a long if isinstance(...) chain grows every time someone adds a type. functools.singledispatch turns it into a registry: you write the default, then register an implementation per type, either by annotation or explicitly. Dispatch is on the type of the first argument and respects inheritance, using the method resolution order. Use singledispatchmethod for methods, where it dispatches on the first argument after self.

Python
from datetime import datefrom decimal import Decimalfrom functools import singledispatch @singledispatchdef to_json(value): raise TypeError(f"cannot serialise {type(value).__name__}") @to_json.registerdef _(value: Decimal): return str(value) # keep precision as a string @to_json.registerdef _(value: date): return value.isoformat() @to_json.register(list)def _(value): return [to_json(v) for v in value] @to_json.register(int)@to_json.register(str)def _(value): return value print(to_json([Decimal("9.99"), date(2026, 10, 22), 3, "ok", True]))try: to_json(1.5)except TypeError as e: print("TypeError:", e)
Output
Press Run (⌘ Enter) to see what happens.

Notice True went through the int implementation, because bool is a subclass of int. Inheritance-aware dispatch is usually what you want, but watch for it. The big advantage over isinstance chains is that other modules can register new types without editing your function, which is how plugin systems and serialisers stay open for extension.

partial and total_ordering, one level deeper

A partial object is not a closure. It stores .func, .args and .keywords as attributes, which makes it inspectable in a debugger, picklable when its function is, and immune to the late-binding trap. Python 3.14 added functools.Placeholder, which lets you leave a positional slot open, so partial(str.replace, Placeholder, " ", "-") fills the second and third arguments and waits for the first.

Python
from functools import partial, Placeholder slugify = partial(str.replace, Placeholder, " ", "-")print(slugify("night train"))print(slugify.args)
Output
Press Run (⌘ Enter) to see what happens.

@total_ordering fills in the missing comparisons when you define __eq__ and one of __lt__, __le__, __gt__ or __ge__. It is convenient, but the generated methods are slower than handwritten ones and give confusing results if your __eq__ and __lt__ disagree. For data classes, @dataclass(order=True) is usually simpler.

Where to go next: recipes and more-itertools

The itertools documentation ends with a page of recipes: tested implementations of sliding_window, grouper, roundrobin, partition, unique_everseen and more. They are not importable from the standard library, so teams copy the ones they need. The more-itertools package on PyPI ships all of them plus many others (chunked, windowed, bucket, peekable, first). Before you write a fiddly generator for a common job, check whether a recipe already exists. Reviewers notice, and the recipe is already debugged.

Match the pairs0/6 matched

Pick the tool for each job.

Choose an item, then its match on the other side.
Key terms
lazy iterator
An object that computes each value only when asked and can be consumed only once.
batched
itertools.batched(it, n) yields tuples of up to n items (3.12); strict=True rejects a short last batch (3.13).
groupby
Groups consecutive items with equal keys; sort by the same key first to get one group per key.
itemgetter
operator.itemgetter(i, ...) builds a fast, picklable key function that fetches items by index or key.
cached_property
Computes a value once per instance and stores it in the instance __dict__; clear with del obj.attr.
singledispatch
Turns a function into a registry of implementations chosen by the type of the first argument.
Placeholder
A sentinel in functools (3.14) that leaves a positional slot open in a partial.