Iterators and batches
from itertools import batched, islice
order_ids = range(101, 111) # a lazy sequence, nothing stored
print(list(islice(order_ids, 3))) # take the first 3
for batch in batched(order_ids, 4): # groups of 4 (Python 3.12+)
print(batch)[101, 102, 103] (101, 102, 103, 104) (105, 106, 107, 108) (109, 110)
Batches are everywhere in pipelines: insert 1,000 rows at a time, call an API with 100 ids per request.
Generator pipelines
read_lines()
yields raw rows
only_delivered()
yields matching rows
amounts()
yields numbers
sum()
pulls until the end
def read_lines(path):
with open(path, encoding="utf-8") as f:
next(f) # skip header
for line in f:
yield line.rstrip("\n").split(",")
def only_delivered(rows):
for r in rows:
if r[5].strip().upper() == "DELIVERED":
yield r
def amounts(rows):
for r in rows:
if r[3].isdigit():
yield int(r[3]) * int(r[4])
# Each step pulls one row at a time: memory stays tiny even for a 50 GB file.
print(sum(amounts(only_delivered(read_lines("data/orders.csv")))))16792
Decorators
import functools, time
def timed(fn):
"""Decorator: print how long a function took."""
@functools.wraps(fn) # keep the original name and docstring
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = fn(*args, **kwargs)
print(f"{fn.__name__} took {time.perf_counter() - start:.2f}s")
return result
return wrapper
@timed # same as: load_orders = timed(load_orders)
def load_orders():
time.sleep(0.2) # pretend work
return 10
print(load_orders(), load_orders.__name__)load_orders took 0.20s 10 load_orders
functools.wraps keeps the original function's name and docstring, so logs and tests still see load_orders.
def retry(times=3, exceptions=(Exception,)):
"""Decorator factory: retry a function on the given exceptions."""
def decorator(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
for attempt in range(1, times + 1):
try:
return fn(*args, **kwargs)
except exceptions as e:
print(f"{fn.__name__} attempt {attempt} failed: {e}")
if attempt == times:
raise
return wrapper
return decorator
state = {"calls": 0}
@retry(times=3, exceptions=(ConnectionError,))
def fetch_rates():
state["calls"] += 1
if state["calls"] < 3:
raise ConnectionError("timeout")
return {"USD_INR": 84.2}
print(fetch_rates())fetch_rates attempt 1 failed: timeout
fetch_rates attempt 2 failed: timeout
{'USD_INR': 84.2}retry(times=3, ...) is a decorator factory: a function that returns a decorator, so the decorator can take settings. Libraries like tenacity provide production-ready versions.
Context managers
from contextlib import contextmanager
@contextmanager
def step(name):
"""Log the start, end and duration of a pipeline step, even if it fails."""
print(f"▶ {name}")
start = time.perf_counter()
try:
yield
finally:
print(f"■ {name} finished in {time.perf_counter() - start:.1f}s")
with step("transform"):
time.sleep(0.1)▶ transform ■ transform finished in 0.1s
The finally inside guarantees the “finished” line even if the step raises. The same idea closes files and commits or rolls back transactions.
Dataclasses: typed records
from dataclasses import dataclass, asdict, field
from datetime import date
@dataclass(frozen=True) # frozen = can't be changed after creation
class Order:
order_id: int
customer_id: int
product: str
quantity: int
price: float
order_date: date
tags: list[str] = field(default_factory=list)
def __post_init__(self): # validation runs on creation
if self.quantity <= 0:
raise ValueError(f"order {self.order_id}: quantity must be > 0")
@property
def amount(self) -> float:
return self.quantity * self.price
o = Order(101, 1, "Headphones", 2, 1999, date(2026, 4, 1))
print(o)
print(o.amount, asdict(o)["product"])Order(order_id=101, customer_id=1, product='Headphones', quantity=2, price=1999, order_date=datetime.date(2026, 4, 1), tags=[]) 3998 Headphones
Order(102, 2, "Charger", 0, 499, date(2026, 4, 1))ValueError: order 102: quantity must be > 0- Fields with types replace hand-written
__init__. __post_init__validates on creation, so an invalid Order can't exist.field(default_factory=list)avoids the shared-mutable-default bug from lesson 4.@propertycomputesamounton demand.
Classes and inheritance
class Step:
"""Base class for pipeline steps."""
name = "step"
def run(self, rows: list[dict]) -> list[dict]:
raise NotImplementedError
class DropCancelled(Step):
name = "drop_cancelled"
def run(self, rows):
return [r for r in rows if r["status"] != "CANCELLED"]
class AddAmount(Step):
name = "add_amount"
def run(self, rows):
return [{**r, "amount": r["quantity"] * r["price"]} for r in rows]
class Pipeline:
def __init__(self, *steps: Step):
self.steps = steps
def run(self, rows):
for s in self.steps:
rows = s.run(rows)
print(f"{s.name}: {len(rows)} rows")
return rows
rows = [{"status": "DELIVERED", "quantity": 1, "price": 1999},
{"status": "CANCELLED", "quantity": 1, "price": 4999},
{"status": "DELIVERED", "quantity": 3, "price": 499}]
print(Pipeline(DropCancelled(), AddAmount()).run(rows))drop_cancelled: 2 rows
add_amount: 2 rows
[{'status': 'DELIVERED', 'quantity': 1, 'price': 1999, 'amount': 1999}, {'status': 'DELIVERED', 'quantity': 3, 'price': 499, 'amount': 1497}]Each step shares the same run() interface, so the Pipeline can chain any steps. Prefer small functions for simple logic; classes help when steps share structure or state.
Copies: alias, shallow, deep
import copy
original = {"order": 101, "items": ["Headphones"]}
alias = original # same object, two names
shallow = copy.copy(original) # new dict, SAME inner list
deep = copy.deepcopy(original) # everything copied
original["items"].append("Charger")
print(alias["items"], shallow["items"], deep["items"])
print(alias is original, shallow is original)['Headphones', 'Charger'] ['Headphones', 'Charger'] ['Headphones'] True False
Threads for I/O
import time
from concurrent.futures import ThreadPoolExecutor
def fetch_page(page: int) -> int:
time.sleep(0.2) # waiting on the network (I/O), not using the CPU
return page
start = time.perf_counter()
results = [fetch_page(p) for p in range(1, 6)]
print(f"one by one: {time.perf_counter() - start:.1f}s")
start = time.perf_counter()
with ThreadPoolExecutor(max_workers=5) as pool:
results = list(pool.map(fetch_page, range(1, 6)))
print(f"5 threads: {time.perf_counter() - start:.1f}s", results)one by one: 1.0s 5 threads: 0.2s [1, 2, 3, 4, 5]
| Work type | Example | Use |
|---|---|---|
| I/O-bound (waiting) | API calls, downloads, DB queries | Threads (ThreadPoolExecutor) or asyncio |
| CPU-bound (computing) | Parsing huge files, heavy maths in Python | Processes (ProcessPoolExecutor), or vectorised libraries |
| Big data | Terabytes | Spark / a warehouse, not Python threads |
🎯 Interview questions on this topic
Try to answer out loud first, then tap to check.
Q1Explain decorators with an example.1–3 yrs+
Q2Iterator vs generator?1–3 yrs+
Q3What is the GIL and how does it affect data pipelines?1–3 yrs+
Q4Why use dataclasses in a pipeline?1–3 yrs+
Q5How would you write a context manager for a database transaction?3+ yrs+
Q6What's the difference between __str__ and __repr__?3+ yrs+
Key takeaways
- ✓Generators and batches keep memory flat for any data size.
- ✓Decorators and context managers remove repeated boilerplate (timing, retries, cleanup).
- ✓Dataclasses make records typed and validated.
- ✓Next: putting everything together into a tested ETL project.
Frequently asked questions
What is a decorator?
A function that takes a function and returns a new function that adds behaviour around it, like timing, retries or logging. @timed above a def is shorthand for func = timed(func).
What is a context manager?
An object used with 'with' that runs setup code before the block and cleanup code after it, even if an error happens. Files, database transactions and locks are context managers.
What is a dataclass?
A class decorator that writes __init__, __repr__ and __eq__ for you from typed fields. Perfect for records like an Order. frozen=True makes instances immutable.
What is the GIL?
The Global Interpreter Lock lets only one thread run Python bytecode at a time in CPython. Threads still speed up I/O-bound work (network, disk), because waiting releases the GIL. For CPU-heavy work, use processes (multiprocessing) or libraries that run outside Python.
Shallow vs deep copy?
A shallow copy makes a new outer object but shares the inner objects; a deep copy copies everything recursively. Changing a nested list affects shallow copies but not deep ones.
🧠 Quick check: advanced Python
1. @retry(times=3) above a function...
2. Threads made 5 network waits take 0.2s instead of 1.0s because...
3. copy.copy(d) then appending to d['items'] changes...
4. @dataclass(frozen=True) means...
Checking your access…