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.
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.
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.
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)))
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.
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.
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.
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.
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.
First run: two lines for 10-21. The key has not changed yet, so they form one group.
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.
created_at. You call groupby(rows, key=lambda r: r.customer_id). What happens?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.
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.
report.total() is called once. The cache key is (self,), so the cache now points at the instance.
Press Run (⌘ Enter) to see what happens.The fixes, in order of preference:
functools.cached_propertywhen the value belongs to one instance. It stores the result in the instance's own__dict__, so it dies with the instance. Clear it withdel obj.attr.- A module-level cached function keyed on plain data (
compute_total(tuple(rows))or an ID), not onself. - A per-instance cache built in
__init__, such asself.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.
PriceCalculator per request and calls calc.quote(sku), decorated with @lru_cache(maxsize=None). Memory grows steadily. Why?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.
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.
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.
Pick the tool for each job.
- 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=Truerejects 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 withdel 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 apartial.