Python Runtime Internals and Production Engineering Practices
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Prompt
Walk through the following nine core areas of CPython runtime behavior and production Python engineering, backing up explanations with brief, idiomatic code examples where requested:
- Global Interpreter Lock (GIL): Explain what the GIL protects inside CPython and why its runtime effect differs sharply between CPU-intensive loops and I/O-waiting operations.
- Concurrency models: Contrast
threading,multiprocessing, andasyncio, giving a concrete workload where each shines along with a minimal code example for all three. - Context managers and decorators: Write and walk through a custom context manager and a custom decorator, and note practical situations where each pattern belongs.
- Iterators and generators: Distinguish iterables from iterators, explain lazy generator execution, and cover sub-generator delegation (
yield from), deterministic generator teardown, and producer-consumer backpressure. - Static typing and data modeling: Explain
PEP 484type annotations,dataclasses, and static checkers such asmypy, illustrating how static analysis catches bugs early and keeps large codebases maintainable. - Environments, packaging, and reproducible builds: Describe how virtual environments (
venv),pip, and pre-built wheel archives (.whl) work together, and how version pinning and cryptographic lockfiles ensure deterministic deployments. - Profiling and performance tuning: Point out frequent Python performance traps, show how to locate bottlenecks with profilers (
cProfile,line_profiler), and explain high-leverage speedups including caching/memoization, NumPy vectorization, PyPy, and compiled C/Rust extensions. - Memory management and leak prevention: Explain how CPython combines reference counting with generational cyclic garbage collection, why memory still grows in long-lived services, and how to detect and prevent object retention leaks.
- Exceptions and error hierarchies: Summarize disciplined exception-handling habits and design a clean, structured hierarchy of custom domain exceptions.
Scope & Expectations
- Connect every runtime claim to concrete CPython mechanics (bytecode execution, GIL release points, reference counts vs cycle detection, and
__annotations__metadata) rather than surface-level slogans. - Provide concise, runnable standard-library Python snippets for concurrency, context management, decorators, generators, typing, profiling, and custom exceptions.
- Highlight subtle production failure modes — such as blocking an event loop, losing function metadata in decorators, unbounded caches pinning objects in RAM, or deploying unpinned transitive dependencies — and how to avoid them.
Step-by-step walkthrough
The GIL and CPU-bound vs I/O-bound workloads
When you run a
.pyfile in CPython (the standard reference Python interpreter written in C), CPython compiles your source code into bytecode (compact, low-level virtual-machine instructions) and executes those instructions in a loop. The Global Interpreter Lock (GIL) is a process-wide mutex (a mutual-exclusion lock that only one thread can hold at any instant) guarding that bytecode loop.Why did CPython choose one global lock? Every Python object carries a reference count in memory; updating fine-grained locks on every integer addition or list lookup slowed single-threaded code and made C extensions fragile, whereas one coarse lock keeps single-threaded Python simple and fast.
How the GIL behaves at runtime determines what speeds up and what stalls:
- Preemptive switching (CPU work): A running thread checks every 5 milliseconds by default (
sys.getswitchinterval() == 0.005) whether another thread is waiting for the GIL, and hands the baton over. - Voluntary release (I/O and C kernels): Whenever a thread starts a blocking operating-system call — reading a socket, querying a database,
time.sleep()— or enters a GIL-releasing C library (numpymatrix math,hashlib,zlib), it releases the GIL immediately so other Python threads can run.
I/O-bound (waiting on network/disk): CPU-bound pure Python (crunching bytecode): Thread 1: [req]..........(waiting)..........[ok] Thread 1: [====GIL====] [====GIL====] Thread 2: [req]..........(waiting)........[ok] Thread 2: [====GIL====] --> Waits overlap: ~Nx faster! --> Strictly takes turns: 0x speedup!Measured on a multi-core machine under default CPython 3.13:
Workload 1 worker Threads (4 or 10) 4 Processes -------------------------------------- -------- ----------------- ----------- 10 x time.sleep(0.2) (I/O-bound) 2.08 s 0.21 s - 4 x countdown from 20M (CPU-bound) 1.52 s 1.53 s 0.72 sKeep two critical nuances straight: - The GIL does NOT make your Python code thread-safe.
counter += 1compiles into separate bytecode steps (loadcounter, add1, storecounter), and a thread switch can land right between load and store, losing updates unless you protect shared mutable state with athreading.Lock. - The GIL is a CPython runtime choice, not a Python language law. CPython 3.13 introduced an optional free-threaded build without the GIL (PEP 703), and Python 3.14 promoted it from experimental to supported (PEP 779), though the standard default build still enables the GIL.- Preemptive switching (CPU work): A running thread checks every 5 milliseconds by default (
Choosing between threading, multiprocessing, and asyncio
Pick your concurrency model by asking "What is my code waiting on, and how many concurrent tasks do I have?"
- Thread (
threading): An operating-system execution unit sharing the same process memory and GIL; best for moderate blocking I/O (10–200concurrent calls) using synchronous libraries likerequestsor standard SQL drivers. - Process (
multiprocessing): A separate OS process with its own Python interpreter, memory space, and GIL; best for CPU-bound pure Python across CPU cores. Inputs and outputs cross processes via pickling (serializing Python objects into byte streams), so pass coarse chunks of work rather than millions of tiny calls. - Coroutine (
asyncio): A lightweight function (async def) driven by a single-threaded event loop (a scheduler that switches tasks only at explicitawaitpoints); best for high-concurrency I/O (1,000–50,000open network connections) with tiny per-task memory overhead.
Model True multi-core CPU? Memory per task Best fit --------------- -------------------- ------------------ ------------------------------------------ threading No (shares 1 GIL) OS stack (~MBs) Blocking I/O with sync libraries (DB/HTTP) multiprocessing Yes (1 GIL/process) Full interpreter CPU-heavy Python loops, parsing, simulation asyncio No (1 OS thread) Coroutine (~KBs) Thousands of concurrent network sockets1.
ThreadPoolExecutorfor blocking I/O:import time from concurrent.futures import ThreadPoolExecutor def fetch_url(url: str) -> str: time.sleep(0.2) # Simulates a blocking HTTP call that releases the GIL return url urls = [f"https://example.com/{i}" for i in range(10)] with ThreadPoolExecutor(max_workers=10) as pool: pages = list(pool.map(fetch_url, urls)) # ~0.21 s wall time instead of ~2.0 s2.
ProcessPoolExecutorfor CPU-bound Python (always guard entry points withif __name__ == "__main__":because on macOS and Windowsspawnstarts fresh Python processes that re-import your script from top to bottom!):from concurrent.futures import ProcessPoolExecutor def count_down(n: int) -> int: while n > 0: n -= 1 return n if __name__ == "__main__": with ProcessPoolExecutor(max_workers=4) as pool: results = list(pool.map(count_down, [20_000_000] * 4))3.
asynciofor thousands of non-blocking network waits (never call blocking functions liketime.sleeporrequests.getdirectly insideasync def— offload unavoidable sync work withawait asyncio.to_thread(fn, ...)):import asyncio async def fetch_item(item_id: int) -> int: await asyncio.sleep(0.2) # Yields control back to the event loop immediately return item_id async def main() -> list[int]: async with asyncio.TaskGroup() as group: tasks = [group.create_task(fetch_item(i)) for i in range(1_000)] return [task.result() for task in tasks] results = asyncio.run(main()) # 1,000 concurrent 0.2 s waits finish in ~0.21 s- Thread (
Custom context managers and decorators
A context manager is an object defining
__enter__(setup before awithblock) and__exit__(exc_type, exc, tb)(guaranteed teardown whether the block succeeds or raises an exception). ReturningFalsefrom__exit__lets any exception propagate normally; returningTruesuppresses it. You can write one as a class or with@contextlib.contextmanager:import time from contextlib import contextmanager class Timer: """Record wall-clock duration of any `with Timer() as t:` block.""" def __enter__(self): self.start = time.perf_counter() return self def __exit__(self, exc_type, exc, tb) -> bool: self.elapsed = time.perf_counter() - self.start return False # Never swallow exceptions raised inside the `with` block @contextmanager def transaction(conn): """Commit on clean exit; roll back and re-raise on any error or Ctrl-C.""" try: yield conn except BaseException: # Catch BaseException (not just Exception) so KeyboardInterrupt also rolls back! conn.rollback() raise else: conn.commit()Common context-manager use cases: closing files/sockets, acquiring and releasing
threading.Locks, database transactions, temporary directory/config overrides (contextlib.chdir), and managing dynamic sets of resources (contextlib.ExitStack).A decorator is a wrapper function that takes a callable and returns an enhanced callable (
@loggedabovedef fmeansf = logged(f)). When a decorator takes configuration arguments (@retry(times=3)), write a decorator factory (an outer function returning the decorator) and always apply@functools.wraps(func)so the original function's__name__,__doc__, type annotations, and__wrapped__pointer are preserved for logs, debuggers, and test frameworks:import functools import time def retry(times: int = 3, base_delay: float = 0.1, exceptions: tuple = (ConnectionError,)): """Retry transient failures with exponential backoff: base_delay, 2x, 4x, ...""" if times < 1: raise ValueError("times must be >= 1") def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): for attempt in range(1, times + 1): try: return func(*args, **kwargs) except exceptions: if attempt == times: raise time.sleep(base_delay * (2 ** (attempt - 1))) return wrapper return decoratorCommon decorator use cases: retry with backoff, memoization (
@functools.lru_cache), authentication/authorization checks, structured request timing, and route registration (@app.get("/health")).Iterators, generators, yield from, cleanup, and backpressure
Python separates containers you can loop over from the cursors that track loop position:
- Iterable: Any object implementing
__iter__()that produces a fresh cursor each time (such as alistordict, which you can loop over repeatedly). - Iterator: A stateful, single-pass cursor implementing
__next__()(returning the next item or raisingStopIteration) and__iter__()(returningself). Once exhausted, a secondforloop over the same iterator yields nothing. - Generator: A function containing
yieldthat builds an iterator using lazy evaluation (computing one item at a time only whennext()asks for it, freezing local variables inO(1)memory between steps — ideal for streaming a 50 GB log file line by line).
Delegating with
yield from:result = yield from sub_gen()forwards every yielded item, as well as.send()and.throw()signals, directly between the outer caller andsub_gen, and capturessub_gen's finalreturnvalue intoresult:def read_chunk(): yield "row-1" yield "row-2" return 2 # Returned count becomes the value of `yield from` def stream_all(): count = yield from read_chunk() yield f"processed {count} rows" assert list(stream_all()) == ["row-1", "row-2", "processed 2 rows"]Generator cleanup: Calling
gen.close()injectsGeneratorExitat the pausedyield, executing any enclosingwithorfinallyblocks so open files close cleanly. Don't rely on garbage collection alone to close an abandoned generator (PyPy delays GC, and async generators needawait aclose()): wrap resource-holding generators incontextlib.closing(gen)(orcontextlib.aclosing(agen)for async generators).Backpressure means slowing a fast producer down when a slow consumer falls behind so buffered items never blow up RAM. Plain synchronous generators give you backpressure automatically because they are pull-based (nothing runs until the consumer calls
next()). In concurrent pipelines, enforce backpressure explicitly with a bounded queue (asyncio.Queue(maxsize=10)orqueue.Queue(maxsize=10)):[Fast Producer] --put() blocks when 10 items queued--> [Bounded Queue (max=10)] --> [Slow Consumer]import asyncio async def producer(q: asyncio.Queue, total: int) -> None: for item in range(total): await q.put(item) # Suspends producer whenever 10 items are already waiting! await q.put(None) # Sentinel signaling end of stream async def consumer(q: asyncio.Queue) -> None: while True: item = await q.get() if item is None: break await asyncio.sleep(0.01) # Simulates slower downstream write- Iterable: Any object implementing
Type hints, dataclasses, and static analysis
Type hints (
PEP 484) attach type metadata (user_id: int -> str | None) that CPython records on__annotations__without enforcing at runtime. Their power comes from static type checking — tools likemypyandpyrightanalyze your source code before it runs to catch type mismatches, unhandledNonereturns, and broken refactors in CI.Using
Protocolenables structural subtyping (checked "duck typing," where any class implementing the required method signature satisfies the interface without inheriting from a shared base class):from typing import Protocol class EmailSender(Protocol): def send(self, recipient: str, subject: str) -> None: ... def lookup_email(user_id: int) -> str | None: return "ada@example.com" if user_id == 1 else None def send_welcome(sender: EmailSender, user_id: int) -> bool: email = lookup_email(user_id) if email is None: # Without this guard, mypy flags `email` in `sender.send(email, ...)` as `str | None`! return False sender.send(email, "Welcome!") return Truedataclassesauto-generate__init__,__repr__, and__eq__from field annotations, eliminating repetitive boilerplate: -frozen=Trueprevents field mutation and makes instances usable asdictkeys orsetmembers. -slots=Truereplaces the per-instance__dict__hash table with a compact fixed-size array, cutting memory and catching misspelled attributes immediately. -field(default_factory=list)gives every instance a fresh list (passingitems: list[str] = []raisesValueErrorat class creation to prevent instances from sharing one mutated list). - Becausedataclassesdo not validate types at runtime (Money("oops", 5)still constructs!), validate untrusted JSON/API inputs at system boundaries using__post_init__checks orpydantic.from dataclasses import dataclass, field @dataclass(frozen=True, slots=True) class Money: cents: int currency: str = "USD" @dataclass class Order: order_id: str tags: list[str] = field(default_factory=list) # Fresh list per Order instancePackaging, environments, and reproducible dependency management
Modern Python packaging separates isolated runtime directories, pre-compiled packages, and two-tier dependency specifications:
venv(python -m venv .venv): Creates an isolated directory with its ownsite-packagesandpipso Project A (SQLAlchemy 1.4) and Project B (SQLAlchemy 2.0) never collide. Pin the Python interpreter version itself via.python-version/uv/ Docker.- Wheels (
.whl) vs source distributions (sdist): A wheel is a pre-built zip archive that unpacks in milliseconds without needing a C/Rust compiler on production servers (tagged likepy3-none-anyfor pure Python orcp313-cp313-manylinux_2_17_x86_64for compiled extensions), whereas an sdist (.tar.gz) executes arbitrary build steps during install. - Direct ranges vs hashed lock files: A transitive dependency is a sub-package pulled in indirectly because one of your direct dependencies needs it. Declare flexible version ranges in
pyproject.toml(so libraries compose cleanly), but deploy applications strictly from a lock file (uv.lock,poetry.lock, orpip-compile --generate-hashes) that pins the exact version and cryptographic SHA-256 hash of every direct and transitive package:
pyproject.toml (human intent) Resolver (uv lock / pip-compile) Lock file (machine truth) ----------------------------- -----------------------------------------> -------------------------------- requests >= 2.31, < 3.0 resolves full dependency graph + SHA-256 requests==2.32.3 (sha256:...) urllib3==2.2.3 (sha256:...) certifi==2024.8.30 (sha256:...)Why not just run
pip freeze > requirements.txt? Becausepip freezedumps whatever ad-hoc packages happen to sit in a developer's local environment without separating top-level intent from transitive dependencies or recording cross-platform hashes. Install in CI and Docker withuv sync --frozenorpip install --require-hashes -r requirements.txt.Profiling performance pitfalls and optimizing hot paths
Never guess where Python spends time — measure first with the right profiler level:
- Deterministic function profiler (
cProfile): Hooks every function entry/exit to reportncalls,tottime(time inside the function itself, excluding subcalls), andcumtime(total time including callees). - Line profiler (
line_profiler/kernprof -l -v): Measures exact time spent on each line inside the hot functioncProfileidentified (crucial when the bottleneck is an inline operator likex in big_listrather than a function call). - Sampling profiler (
py-spy): Periodically snapshots a running process's call stack from outside with near-zero overhead — safe to attach to live production services.
import cProfile import functools import pstats def slow_unique(items: list[int]) -> list[int]: seen: list[int] = [] for item in items: if item not in seen: # O(n) linear scan per element -> O(n^2) total! seen.append(item) return seen def fast_unique(items: list[int]) -> list[int]: return list(dict.fromkeys(items)) # O(1) average hash lookup -> O(n) total @functools.lru_cache(maxsize=256) def fib(n: int) -> int: return n if n < 2 else fib(n - 1) + fib(n - 2) sample = list(range(5_000)) * 2 with cProfile.Profile() as prof: slow_unique(sample) fast_unique(sample) pstats.Stats(prof).sort_stats("tottime").print_stats(4)Optimize in descending order of leverage (measured on CPython 3.13):
Optimization lever Concrete example Measured impact --------------------------------------- --------------------------------------- ----------------------------- 1. Fix O(n^2) data structures first `x in list` -> `x in set` (100k items) 280 us -> 0.02 us (14,000x) 2. Memoize repeated pure subproblems `@lru_cache` on `fib(30)` 2,692,537 calls -> 31 runs 3. Vectorize numeric loops into C Python loop -> `np.dot(a, a)` (1M floats) 12.0 ms -> 0.20 ms (60x) 4. Batch strings and network/DB roundtrips `"".join(parts)` and batched SQL `IN` Eliminates quadratic copies / N+1 5. Upgrade runtime or hot kernel PyPy JIT (pure Python) / Cython / PyO3 3x-50x on tight inner loops(Memoization caches a pure function's outputs by its arguments; vectorization hands whole arrays to compiled C/SIMD loops instead of interpreting bytecode per element; a JIT compiler like PyPy translates hot Python loops into machine code at runtime.)
- Deterministic function profiler (
Memory management, leak prevention, and custom exceptions
CPython manages memory with two cooperating layers:
- Reference counting (immediate cleanup): Every object stores a counter of active references pointing to it. The instant that count drops to
0, CPython frees the object immediately. - Cyclic garbage collector (
gcmodule): If two objects point to each other (parent.child = c; c.parent = parent), they form a reference cycle whose counts stay>= 1even after external variables vanish. The generational cyclic GC periodically traverses container objects (list,dict, custom instances), detects unreachable islands, and frees them.
In Python, "memory leaks" are almost always lingering references that keep objects reachable forever: -
@lru_cache(maxsize=None)or module-level dicts growing without a bound or TTL (especially@lru_cacheon instance methods, which pinsselfinside the cache key forever!). - Event listeners registered and never unsubscribed, or stored exception__traceback__objects pinning entire stack frames in memory. - How to diagnose and fix: Take twotracemalloc.take_snapshot()snapshots minutes apart and callafter.compare_to(before, "lineno")to pinpoint growing lines; inspect holders viagc.get_referrers(obj); use weak references (weakref.WeakValueDictionary, references that let an object be garbage-collected when normal references disappear) and__slots__(shrinking a 2-field CPython 3.13 instance from88bytes to48bytes).Exception handling and custom exception design: - Catch the most specific exception you can recover from; never write bare
except:(which catchesKeyboardInterruptandSystemExit) or silentexcept Exception: pass. - Keeptryblocks narrow, put success-only follow-up code inelse, and put resource cleanup inwith/finally. - At module boundaries, wrap low-level errors using exception chaining (raise GatewayTimeout(...) from err), which preserves the root cause on__cause__in tracebacks (and useExceptionGroup/except*when handling concurrentTaskGroupfailures). - Give your domain one baseExceptionsubclass, specific subclasses for actionable failure modes, structured attributes (so callers never parse error strings!), and pass all init arguments tosuper().__init__(...)so exceptions survivemultiprocessingpickling:class PaymentError(Exception): """Base exception for all payment-domain failures.""" class InsufficientFundsError(PaymentError): """Caller should prompt the user to add funds (do not retry blindly).""" def __init__(self, account_id: str, shortfall_cents: int) -> None: # Passing all fields to super().__init__ keeps the exception picklable across processes! super().__init__(account_id, shortfall_cents) self.account_id = account_id self.shortfall_cents = shortfall_cents def __str__(self) -> str: return f"Account {self.account_id} is short by {self.shortfall_cents} cents" class GatewayTimeoutError(PaymentError): """Transient upstream timeout; safe for caller to retry with backoff.""" def charge_card(gateway, account_id: str, cents: int) -> None: try: gateway.charge(account_id, cents) except TimeoutError as err: raise GatewayTimeoutError(f"Timed out charging {account_id}") from err- Reference counting (immediate cleanup): Every object stores a counter of active references pointing to it. The instant that count drops to
Intuition & how it works
Picture CPython as a restaurant kitchen with one wooden cooking spoon — the Global Interpreter Lock (GIL) (a mutex ensuring only one thread executes Python bytecode at a time). If four chefs share that one kitchen (threading) and all four need to chop vegetables non-stop (CPU-bound pure Python), they merely pass the single spoon back and forth every 5 milliseconds and finish no faster than one chef working alone. However, whenever a chef puts a pot in the oven and waits 10 minutes for a timer (I/O-bound network or disk calls), they set the spoon down, letting dozens of chefs overlap their waiting times (threading or asyncio) — and when you genuinely need four chefs chopping simultaneously, you open four separate kitchens (multiprocessing).
Naive Python code breaks in production whenever developers fight the runtime instead of working with its contracts. Spawning threads on CPU-heavy Python loops wastes context-switching time for zero speedup, while calling a single synchronous requests.get() inside an async def handler freezes every other coroutine on the event loop. Likewise, skipping with context managers, @functools.wraps, bounded queues, hashed lock files, or tracemalloc profiling leads to leaked connections, corrupted tracebacks, out-of-memory crashes when traffic spikes, and unrepeatable deployments.
Trace a concrete request pipeline that fetches 10 user profiles (200 ms network wait each) and deduplicates 5,000 item IDs per profile:
- Naive sequential code: Waiting on 10 HTTP calls back-to-back spends
2.08 s, and deduplicating withif item not in seen_list(O(n^2)list scans) burns ~0.85 sof CPU (~2.93 stotal). - Concurrency + right data structure: Overlapping the 10 network waits with
ThreadPoolExecutor(max_workers=10)releases the GIL during socket waits and drops I/O wall time to0.21 s; replacing the list scan withlist(dict.fromkeys(items))(O(1)hash lookups) cuts CPU work below0.002 s— a >13x speedup verified directly withcProfile.
Key points
- GIL & workload matching: CPython's GIL serializes Python bytecode (virtual-machine instructions) within one process while releasing around blocking I/O and native C kernels (
numpy,hashlib). Usethreadingfor moderate blocking I/O (2.08 s -> 0.21 s),multiprocessing(with coarse work chunks andif __name__ == "__main__":) for CPU-bound Python (1.52 s -> 0.72 son 4 cores), andasynciocoroutines (lightweight tasks paused atawaiton a single-threaded event loop) for thousands of concurrent network sockets. - Context managers & decorators: Context managers (
__enter__/__exit__or@contextmanagerwithtryaroundyield) guarantee deterministic teardown even on exceptions (__exit__returningFalselets errors propagate). Decorators wrap callables cleanly when paired with@functools.wraps(preserving__name__,__doc__, and__wrapped__) and a factory layer for parameters. - Generators & backpressure: Generators (
yield) implement single-pass iterators via lazy evaluation inO(1)memory;yield fromdelegates items, signals, and return values to sub-generators;contextlib.closing/aclosingensures deterministic cleanup. Backpressure (slowing a fast producer so slow consumers never exhaust RAM) is automatic in pull-based generators and enforced in concurrent code via bounded queues (asyncio.Queue(maxsize=N)). - Static typing & dataclasses: Type hints (
PEP 484,Protocolfor structural duck typing,str | Noneunions) are verified ahead of time by static type checkers (mypy,pyright) rather than enforced at runtime.@dataclass(frozen=True, slots=True)andfield(default_factory=list)eliminate boilerplate safely, whilepydanticor__post_init__handles runtime validation on untrusted external input. - Packaging & reproducible builds: Isolate projects with
venv, ship pre-built wheels (.whl) instead of uncompiled source archives (sdist), declare version ranges inpyproject.toml, and deploy applications strictly from a lock file (uv.lock/pip-compile --generate-hashes) pinning exact direct and transitive dependencies (indirect sub-packages) with SHA-256 hashes. - Profiling before optimizing: Locate hot functions with
cProfile(tottimevscumtime), hot lines withline_profiler, and live production bottlenecks withpy-spy(a low-overhead sampling profiler). FixO(n^2)algorithms (list->set), apply memoization (@lru_cachewith a boundedmaxsize), vectorize numeric work in NumPy, and reach for PyPy's JIT compiler or Cython/Rust extensions only for proven inner-loop bottlenecks. - Memory & exceptions: CPython combines immediate reference counting with a generational cyclic garbage collector (
gc) for reference cycles; diagnose lingering-reference leaks withtracemallocsnapshot diffs andweakref/__slots__. Catch narrow exceptions, chain domain errors withraise CustomError(...) from err, and pass all fields tosuper().__init__(...)so custom exceptions remain picklable.
Common mistakes
- Assuming the GIL makes
counter += 1ordictcheck-then-set atomic. Thread switches happen between bytecode instructions; shared mutable state still requiresthreading.Lockor thread-safe queues. - Calling blocking I/O (
time.sleep,requests.get, sync DB drivers) insideasync def. One blocking call stalls the entire single-threaded event loop; use async clients orawait asyncio.to_thread(...). - Omitting
if __name__ == "__main__":when creating aProcessPoolExecutor. Under thespawnstart method (default on macOS and Windows), worker processes re-import the main module and trigger recursive pool creation (RuntimeError/BrokenProcessPool). - Writing
@contextmanagerwithouttry ... finallyaroundyield, or returning a truthy value from__exit__. Withouttry, exceptions raised inside thewithblock skip your cleanup code; returningTruefrom__exit__silently swallows every exception! - Forgetting
@functools.wrapsor using mutable default arguments (def f(items=[])). Unwrapped decorators turn every function name intowrapperin stack traces, and a default list is evaluated once atdeftime and mutated across all calls. - Looping over an iterator or generator twice. Unlike a
list, a generator is exhausted after one pass, so the secondforloop silently processes zero items. - Putting
@lru_cache(maxsize=None)on an instance method. Becauseselfis part of the cache key, the global cache holds a strong reference to every instance forever, creating a classic Python memory leak. - Using bare
except:,except Exception: pass, orraise DomainError(str(err))withoutfrom err. Bareexcept:trapsCtrl-C,passhides production bugs, and omittingfrom errobscures deliberate error translation in tracebacks.
Follow-up questions
- How do free-threaded CPython builds (PEP 703 and PEP 779) change how you choose between threads and processes? Starting in Python 3.13 (experimental) and 3.14 (officially supported optional build,
python3.14t), CPython can run without the GIL using biased reference counting and fine-grained internal locks (sys._is_gil_enabled()reports whether the GIL is active). On a free-threaded build,threadingfinally achieves multi-core parallelism on CPU-bound pure Python withoutmultiprocessing's pickling overhead, though importing a legacy C extension that hasn't declared free-threading support automatically re-enables the GIL at runtime with a warning. Even more importantly, removing the GIL exposes data races that the GIL previously masked by accident, making strictLockdiscipline and immutable data structures mandatory. - How would you track down a gradual memory leak in a live Python web service without restarting it blindly? First check container RSS memory alongside request rate to confirm memory keeps climbing during flat traffic rather than simply plateauing due to allocator fragmentation. Next, trigger an admin diagnostic endpoint (or
memrayif C extensions are suspected) that callstracemalloc.start(), captures two snapshots 15 minutes apart, and logssnap2.compare_to(snap1, "lineno")[:10]to reveal the exact file and line whose live object count keeps growing. Once you spot the growing type,gc.get_referrers(sample_obj)shows which unbounded cache, callback list, or global registry is pinning those objects alive. - If you needed to fetch 10,000 partner URLs without exhausting RAM or overloading upstream hosts, would you choose threads or asyncio? Because fetching 10,000 URLs is overwhelmingly network I/O-bound,
asynciowith an async HTTP client (httpx.AsyncClientoraiohttp) and a shared connection pool is ideal, though aThreadPoolExecutor(max_workers=50)works cleanly too if the rest of the codebase is synchronous. In either model, enforce backpressure and polite rate-limiting with a semaphore (asyncio.Semaphore(50)) or bounded work queue (asyncio.Queue(maxsize=200)), stream parsed records directly to disk/DB instead of accumulating 10,000 HTML pages in a list, and wrap each request with explicit connect/read timeouts plus exponential-backoff retries on transient5xx/ timeout errors. If HTML parsing turns out to saturate the single event-loop CPU core, offload batches of raw HTML to a smallProcessPoolExecutor.
Follow-up questions
- How do free-threaded CPython builds (PEP 703 and PEP 779) change how you choose between threads and processes?
- How would you track down a gradual memory leak in a live Python web service without restarting it blindly?
- If you needed to fetch 10,000 partner URLs without exhausting RAM or overloading upstream hosts, would you choose threads or asyncio?
Similar questions
- Longest Repeat-Free Substring
- Cloud Architecture and Operations Fundamentals
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance