Python Deep Dive: Concurrency, Generators, Typing and Memory
Data Structure DesignModel answerLast updated
Nine-part Python fundamentals review covering the GIL, concurrency models, decorators, generators, typing, packaging, profiling, memory management and exceptions.
You are given a Python fundamentals round. Prepare a clear, spoken-length answer (roughly one to two minutes each) for every item below, with a short code snippet where one is asked for.
- The GIL. What is it, and how does it affect CPU-bound versus I/O-bound workloads?
- Threads, processes, asyncio. Compare the three and give a scenario and a short snippet for each.
- Context managers and decorators. Write one of each from scratch and name typical uses.
- Iterators and generators. Cover
yield from, what happens when a generator is abandoned, and how to get backpressure. - Static typing. Discuss PEP 484 hints,
dataclassesand a checker such as mypy, and explain how they help maintainability. - Packaging and environments. Cover virtual environments, pip, wheels, and how to make dependency installs reproducible.
- Performance. Name common pitfalls, show how to profile (
cProfile,line_profiler), and list optimization options. - Memory management. Explain reference counting and the cyclic collector, and how leaks still happen.
- Exceptions. Describe good handling practices and how to design custom exception types.
Be explicit about assumptions (CPython, version), mention trade-offs, and say how you would verify each claim.
Hints
Hint 1
For the GIL, think about when the running thread gives it up: blocking system calls and some C extensions release it, pure-Python bytecode loops do not.
Hint 2
For generators, ask what is still paused inside the frame when the consumer walks away, and which exception is raised at the paused yield when it is closed.
Hint 3
For leaks, remember that reference counting frees most objects immediately, so look for something that keeps a reference alive: module-level caches, closures, registered callbacks, or unbounded collections.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. The GIL
In CPython the Global Interpreter Lock is a mutex that lets only one thread execute Python bytecode at a time. It exists to keep reference counting and interpreter internals safe without fine-grained locks. A running thread is asked to yield roughly every 5 ms (sys.getswitchinterval()).
- CPU-bound pure Python: threads give no speedup, and contention can make them slower.
- I/O-bound work: the lock is released during blocking calls (sockets, file reads,
time.sleep), so threads overlap well. - C extensions: NumPy,
zlibandhashlibrelease the GIL for heavy work, so threads can scale there.
Worth noting: Python 3.12 added per-interpreter GILs (PEP 684), and 3.13 ships an experimental free-threaded build (PEP 703). Neither changes the default advice yet.
2. Threads vs processes vs asyncio
| Model | Use when | Cost |
|---|---|---|
threading | Blocking I/O, sync-only libraries | Shared state needs locks; no CPU parallelism |
multiprocessing | CPU-bound Python | Startup cost, pickling of arguments/results, no shared memory by default |
asyncio | Thousands of concurrent I/O waits | Needs async-aware libraries; one blocking call stalls the whole loop |
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
import asyncio
def download(url): ... # blocking I/O
def heavy(n): return sum(i * i for i in range(n))
with ThreadPoolExecutor(16) as ex: # I/O-bound
pages = list(ex.map(download, urls))
if __name__ == "__main__":
with ProcessPoolExecutor() as ex: # CPU-bound
out = list(ex.map(heavy, [10**7] * 8))
async def crawl(urls):
sem = asyncio.Semaphore(100) # cap concurrency
async def one(u):
async with sem:
await asyncio.sleep(0.1) # stand-in for an async HTTP call
return u
return await asyncio.gather(*(one(u) for u in urls))
Escape hatches: loop.run_in_executor or asyncio.to_thread for blocking calls inside async code.
3. Context manager and decorator
import contextlib, functools, os, time
@contextlib.contextmanager
def pushd(path):
prev = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(prev) # always restored
class Stopwatch:
def __enter__(self):
self.t0 = time.perf_counter(); return self
def __exit__(self, et, ev, tb):
self.elapsed = time.perf_counter() - self.t0
return False # truthy would swallow the exception
def retry(attempts=3, on=(OSError,), base=0.1):
def deco(fn):
@functools.wraps(fn) # keep name, docstring, signature info
def wrapper(*a, **kw):
for i in range(attempts):
try:
return fn(*a, **kw)
except on:
if i == attempts - 1:
raise
time.sleep(base * 2 ** i)
return wrapper
return deco
__exit__ receives the in-flight exception; suppress it only on purpose. Typical uses: locks, files, transactions, temporary settings (context managers); retries, caching, auth, metrics, registries (decorators).
4. Iterators and generators
An iterable has __iter__; an iterator has __next__ and raises StopIteration at the end. A generator function builds an iterator lazily, suspending its frame at each yield.
def lines(path):
with open(path) as f:
for ln in f:
yield ln.rstrip("\n")
def counted(path):
n = 0
for _ in lines(path): n += 1
return n
def outer(path):
n = yield from inner(path) # delegates next/send/throw/close; captures return value
yield fromforwardssend,throwandcloseto the sub-generator and evaluates to its return value.- Cleanup:
close()(or garbage collection of an unfinished generator) raisesGeneratorExitat the pausedyield, sofinallyandwithblocks run. Do not yield again while handling it. - Backpressure: generators are pull-based, so the producer works only when the consumer asks and memory stays bounded. In async pipelines use
asyncio.Queue(maxsize=N);await q.put()suspends fast producers when the queue is full.
5. Typing, dataclasses, mypy
Hints are not enforced at runtime; mypy or pyright check them statically.
from dataclasses import dataclass, field
from typing import Protocol
@dataclass(frozen=True, slots=True)
class Product:
sku: str
cents: int
labels: list[str] = field(default_factory=list) # never a bare [] default
class Catalog(Protocol):
def find(self, sku: str) -> Product | None: ...
def price_of(cat: Catalog, skus: list[str]) -> int:
return sum(p.cents for s in skus if (p := cat.find(s)))
Benefits: signatures act as checked documentation, renames surface every broken caller, None handling is verified, and Protocol allows structural typing so code depends on behavior. Adopt gradually: strict mode on new modules, run in CI.
6. Packaging and environments
- One
python -m venv .venvper project; never install into system Python. - Wheels are prebuilt and install fast with no compiler; sdists may need a build step.
- Declare loose, abstract requirements in
pyproject.toml; lock exact transitive versions with hashes for applications (pip-compile --generate-hashes,poetry.lock,uv.lock). - Install with
pip install --require-hashes -r requirements.txt, pin the Python version, and build one artifact or container in CI and deploy that. - Libraries keep ranges loose; applications lock. Automate updates (Dependabot/Renovate) and scan with
pip-audit.
7. Performance
Measure first.
python -m cProfile -s cumtime app.py # which functions
kernprof -l -v app.py # which lines (@profile on the target)
Pitfalls: x in list inside loops (use a set), string += in loops (use join), iterrows in pandas, repeated global/attribute lookups in hot loops, and needless copies. Fixes: better algorithms first, then vectorization (NumPy), functools.lru_cache, generators to avoid materializing data, C extensions (Cython, Rust bindings), or PyPy for long-running pure-Python code.
8. Memory management
CPython frees objects the moment their reference count hits zero. The cyclic garbage collector (gc) handles reference cycles that counting cannot. Leaks in practice are objects that stay reachable:
- Unbounded module-level caches or lists; use
lru_cache(maxsize=...)or a bounded structure. - Closures, bound-method callbacks and listeners never unregistered; use
weakref(WeakValueDictionary,WeakSet). - Exception tracebacks held in variables, which keep frames alive.
- Cycles with
__del__or native resources that are not closed.
Diagnose with tracemalloc snapshots (diff over time), gc.get_objects() counts, or objgraph. Close resources with with.
9. Exceptions
- Catch specific exceptions; avoid bare
except:and swallowing errors silently. - Keep
tryblocks small; useelsefor the success path andfinallyfor cleanup. - Chain with
raise NewError(...) from errto preserve causes; use bareraiseto re-raise unchanged. - Define a base class per library and subclass it:
class PaymentError(Exception): ...
class CardDeclined(PaymentError):
def __init__(self, code: str):
super().__init__(f"declined: {code}")
self.code = code
Callers can catch the whole family or one case. Derive from Exception, not BaseException, and attach structured data rather than parsing messages.
Common mistakes
Claiming threads speed up CPU-bound Python; blocking the event loop in a coroutine; forgetting functools.wraps; mutable default arguments; assuming type hints are checked at runtime; and optimizing without profiling.