Iterators, generators, decorators & functional tools
The iterator protocol, generator functions, decorators, closures and functional idioms.
The iterator protocol behind for loops
Every for loop is sugar for iter() and repeated next(); understanding this lets you build your own iterables.
An iterable implements __iter__, returning an iterator; an iterator implements __iter__ (usually returning itself) and __next__, which returns the next value or raises StopIteration once exhausted. A for item in obj: loop is exactly equivalent to calling iter(obj) once, then calling next() on the result repeatedly until StopIteration is caught and silently stops the loop. Implementing this protocol on your own class lets instances of it be used directly in for loops, list(), and anywhere else Python expects an iterable, without any special-casing.
Key points
- Iterable implements __iter__ returning an iterator; iterator implements __iter__ and __next__
- for is sugar for iter() once, then next() repeatedly until StopIteration
- Implementing the protocol lets your own class work in for loops, list(), and comprehensions
Code
Run the code to see the result.
A hand-written iterator class that works directly in a for loop by implementing __iter__ and __next__.
Common pitfalls
- Forgetting to raise StopIteration eventually makes the iterator (and any for loop over it) run forever
- An object with only __getitem__ but no __iter__ can still work with for in some cases via a legacy fallback, which surprises people relying on the modern protocol
Practice exercise
Write an iterator class Evens(limit) that yields only even numbers from 0 up to (not including) limit, implementing __iter__ and __next__ by hand.
Generator functions and yield
yield turns a function into a lazy value producer, radically simpler to write than a manual iterator class.
Any function containing at least one yield becomes a generator function: calling it does not run the body, it returns a generator object that already implements the full iterator protocol automatically. Each next() call resumes the function from where it last paused, runs until the next yield, and returns that value, preserving all local state (variables, loop position) between resumptions. This makes generators dramatically simpler to write than the equivalent hand-rolled iterator class from the previous lesson, while staying just as memory-efficient, since values are produced one at a time instead of all at once.
Key points
- Any function with yield becomes a generator function; calling it returns a generator, not a result
- Each next() resumes execution right after the last yield, with all local state preserved
- Generators implement the iterator protocol automatically, far less code than a manual class
Code
Run the code to see the result.
The same even-numbers logic as the earlier iterator class, expressed in four lines with yield.
Common pitfalls
- A generator can only be iterated once — a second for loop over the same exhausted generator yields nothing
- Calling a generator function does not run any code inside it until the first next() or the first iteration
Practice exercise
Rewrite the Evens(limit) iterator class from the previous lesson as a generator function using yield, and confirm it produces the same values.
Writing your own decorators
@decorator is sugar for func = decorator(func); a decorator wraps a function to add behavior around it.
A decorator is a callable applied to a function or class definition: it receives the defined object, and whatever it returns is rebound to the original name. The most common pattern is a function that takes another function and returns a wrapper that calls the original and adds behavior before or after it — but a decorator does not have to be a plain function, and its return value does not have to be a wrapper at all; a registration decorator, for example, can simply record the function in a registry and return it completely unchanged. Writing @timer directly above def slow_task(): is exactly equivalent to defining slow_task normally and then writing slow_task = timer(slow_task) — the @ syntax is just a readable shorthand for that rebinding. For the common wrapper-returning pattern, using functools.wraps(func) inside the wrapper preserves the original function's __name__ and __doc__, which matters for debugging, introspection, and tools that display function names.
Key points
- @decorator above a function is sugar for func = decorator(func)
- A decorator's return value replaces the original name; a wrapper calling the original is one common pattern, not a requirement
- functools.wraps(func) inside the wrapper preserves __name__ and __doc__
Code
Run the code to see the result.
A reusable timer decorator that measures and prints any decorated function's execution time.
Common pitfalls
- Forgetting args, *kwargs in the wrapper breaks decorating any function that takes arguments
- Skipping functools.wraps makes decorated_func.__name__ report "wrapper" instead of the real function name
Practice exercise
Write a @log_calls decorator that prints the function name and its arguments every time the decorated function is called, using functools.wraps correctly.
Closures: functions that remember their environment
An inner function can capture and reuse variables from its enclosing function even after that function returns.
When a function defined inside another function references a variable from the outer function's scope, Python keeps that variable alive as part of a closure even after the outer function has already returned — the inner function "closes over" that variable. This is the mechanism behind decorators and behind factory functions that produce customized functions, like a make_multiplier(factor) that returns a function remembering its own factor. To modify (not just read) an enclosing variable from inside the inner function, you must declare it nonlocal first.
Key points
- An inner function captures variables from its enclosing scope, kept alive after the outer function returns
- Factory functions like make_multiplier(factor) use closures to produce customized functions
- Modifying (not just reading) an enclosing variable requires an explicit nonlocal declaration
Code
Run the code to see the result.
Two independent closures, each remembering its own factor from when make_multiplier was called.
Common pitfalls
- Closures created inside a loop that reference the loop variable directly all share the same final value once called
- Trying to reassign an enclosing variable inside the inner function without nonlocal creates a new local variable instead
Practice exercise
Write make_counter() that returns a function which increments and returns an internal count each time it's called, using nonlocal to modify the enclosed count variable.
First-class functions and functional idioms
Functions are values like any other; this enables passing behavior around, not just data.
Because functions are first-class objects in Python, they can be stored in variables and data structures, passed as arguments, and returned from other functions — this is what makes sorted(items, key=some_function), map(), filter(), and decorators possible at all. A dict mapping strings to functions ({"add": add, "sub": subtract}) is a common, readable alternative to a long if/elif chain when dispatching behavior by name. List comprehensions are generally preferred over map()/filter() in modern Python for readability, but understanding the functional versions still helps when reading library code or working with tools that expect a plain callable.
Key points
- Functions can be stored, passed, and returned like any other value
- A dict of name-to-function mappings is a clean alternative to a long if/elif dispatch chain
- Comprehensions are generally preferred over map()/filter() for readability in modern code
Code
Run the code to see the result.
Dispatching behavior through a dict of functions instead of a chain of if/elif statements.
Common pitfalls
- operations["*"](5, 3) raises KeyError for an operator not in the dict — validate the key first, or use .get() with a fallback
- Overusing dict-based dispatch for only two or three simple cases can be less readable than a short if/elif
Practice exercise
Extend the calculate() dispatch dict with multiplication and division operators, handling division by zero and an unknown operator with clear error messages.