Generators & `yield`
Advanced Iteration
Generators Make Data Streams
Generators produce values on demand, minimize memory usage, and support coroutine-style communication.
Basics
def read_in_chunks(path, chunk_size=1024):
with open(path, 'rb') as fh:
while chunk := fh.read(chunk_size):
yield chunk
- Use
yieldto pause a function and resume later. - Generators automatically implement the iterator protocol.
yield from
def flatten(sequences):
for seq in sequences:
yield from seq
- Delegates to another iterable without manual loops.
Generator expressions
total = sum(price for price in prices if price > 0)
- Parentheses produce a generator expression.
- Perfect feed for
sum,any,all,max, etc.