Python Interview Questions
Python internals interview guide covering GIL mechanics, reference counting garbage collection, generators, asyncio event loops, and typing.
Practice Python Interview Questions
Showing 16 of 16 technical questions with engineering explanations
Why are mutable default arguments dangerous in Python functions, and how do you fix them idiomatically?
Senior Engineering Answer
In Python, default parameter expressions are evaluated once when the def statement executes, not each time the function is called. The resulting object is stored in function.__defaults__ and shared across every invocation that omits that argument. If the default is a mutable object such as a list or dict, mutations in one call persist into subsequent calls. The idiomatic fix is to use None as the sentinel default and allocate a fresh container inside the function body.
def append_tag(tag: str, tags: list[str] | None = None) -> list[str]:
if tags is None:
tags = []
tags.append(tag)
return tags
print(append_tag("api")) # ['api']
print(append_tag("auth")) # ['auth'] (independent list)Do not confuse mutable defaults with immutable defaults like tuples or strings, which are safe because they cannot be mutated in place. Also note that dataclasses use field(default_factory=list) for the exact same reason.
What is the difference between '==' and 'is' in Python, and why do small integers or short strings sometimes behave inconsistently with 'is'?
Senior Engineering Answer
The '==' operator checks value equality by invoking the object's __eq__ dunder method, whereas 'is' checks object identity by comparing memory pointers (equivalent to id(a) == id(b)). CPython interns small integers (typically -5 through 256) and some compile-time string literals as an optimization, so two variables holding 42 may happen to share the same object identity while 1000 will not. Always use 'is' only for singletons such as None, True, False, or sentinel objects, and use '==' for value comparisons.
a = 256
b = 256
print(a is b) # True (CPython small-int cache)
x = int("1000")
y = int("1000")
print(x == y) # True (same value)
print(x is y) # False (distinct objects)
if value is None:
passNever rely on 'is' for string or integer comparison even if it passes in the REPL; constant folding in compiled modules can share literals that runtime expressions will not.
How does Python pass arguments to functions: pass-by-value or pass-by-reference?
Senior Engineering Answer
Python uses pass-by-object-reference (also called call-by-sharing). Every argument passes a reference to the existing object, bound to the parameter name in the callee's local namespace. Reassigning the parameter name inside the function only rebinds the local name to a new object and never affects the caller's variable. However, mutating a mutable object in place (such as list.append or dict.__setitem__) modifies the shared object visible to the caller.
def mutate_and_rebind(items: list[int], count: int) -> None:
items.append(4) # mutates caller's list in place
items = [99] # rebinds only local parameter
count += 1 # int is immutable; rebinds local name
nums = [1, 2, 3]
n = 10
mutate_and_rebind(nums, n)
print(nums, n) # [1, 2, 3, 4] 10Saying 'primitives are pass-by-value and objects are pass-by-reference' is inaccurate in Python: integers and strings are objects too, passed by object reference, and only appear value-like because they are immutable.
What are the memory and control-flow differences between a list comprehension and a generator expression?
Senior Engineering Answer
A list comprehension eagerly evaluates every element immediately and allocates a full list in memory (O(N) space). A generator expression returns a lazy iterator object that computes one item per __next__() call and suspends its stack frame between yields, using O(1) auxiliary memory. Unlike lists, generators are single-pass: once exhausted, iterating over them again yields nothing and cannot be indexed or measured with len().
# Eager: materializes 1M integers in RAM
squares_list = [x * x for x in range(1_000_000)]
# Lazy: O(1) memory, computes on demand
total = sum(x * x for x in range(1_000_000))
gen = (line.strip() for line in open("events.log"))
first_five = [next(gen) for _ in range(5)]Passing a generator expression to a function that iterates twice (or checks bool/len before iterating) silently produces empty results on the second pass.
How do you write a parameterized Python decorator without losing the wrapped function's metadata or signature?
Senior Engineering Answer
A parameterized decorator is a three-level callable: an outer factory accepts configuration arguments and returns the actual decorator, which receives the target function and returns a wrapper function. Applying @functools.wraps(func) to the inner wrapper copies __name__, __doc__, __module__, __annotations__, and sets __wrapped__ so inspect.signature(), Sphinx docs, and pytest fixtures see the original function metadata.
import functools
import time
from collections.abc import Callable
from typing import ParamSpec, TypeVar
P = ParamSpec("P")
R = TypeVar("R")
def retry(attempts: int = 3, delay: float = 0.1) -> Callable[[Callable[P, R]], Callable[P, R]]:
def decorator(func: Callable[P, R]) -> Callable[P, R]:
@functools.wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
for i in range(attempts):
try:
return func(*args, **kwargs)
except RuntimeError:
if i == attempts - 1:
raise
time.sleep(delay)
raise AssertionError("unreachable")
return wrapper
return decoratorForgetting @functools.wraps breaks debugging tracebacks, serialization, and frameworks like FastAPI or Click that inspect function signatures and annotations.
How does the Python context manager protocol work, and when should you use contextlib.ExitStack?
Senior Engineering Answer
A context manager implements __enter__() and __exit__(exc_type, exc_val, exc_tb). On entering a with block, __enter__ runs and its return value binds to the 'as' target. On leaving the block—normally or via exception—Python guarantees __exit__ runs; if __exit__ returns a truthy value, the exception is suppressed. When the number of resources to manage is dynamic (such as opening N files or conditional locks), contextlib.ExitStack lets you register context managers programmatically and guarantees LIFO teardown.
from contextlib import ExitStack, contextmanager
from collections.abc import Iterator
@contextmanager
def temp_flag(state: dict[str, bool], key: str) -> Iterator[None]:
prev = state.get(key, False)
state[key] = True
try:
yield
finally:
state[key] = prev
def merge_files(paths: list[str]) -> list[str]:
with ExitStack() as stack:
handles = [stack.enter_context(open(p, "r", encoding="utf-8")) for p in paths]
return [h.read() for h in handles]In a @contextmanager generator, failing to wrap the yield in try/finally causes cleanup code after yield to be skipped whenever the caller's with-block raises an exception.
What does __slots__ do on a Python class, and what are its trade-offs with inheritance and weak references?
Senior Engineering Answer
By default, Python stores each instance's attributes in a per-instance hash table (__dict__), which adds significant memory overhead when millions of small objects exist. Defining __slots__ tells CPython to allocate a fixed-size C struct array of descriptors directly on the instance instead of a __dict__, cutting per-object RAM usage by roughly 40-60% and slightly speeding up attribute access. Trade-offs include disallowing arbitrary dynamic attributes, requiring subclasses to also define __slots__ (otherwise a __dict__ is recreated), and omitting __weakref__ unless explicitly listed in __slots__.
class Point:
__slots__ = ("x", "y", "__weakref__")
def __init__(self, x: float, y: float) -> None:
self.x = x
self.y = y
p = Point(1.0, 2.0)
# p.z = 3.0 # raises AttributeError: 'Point' object has no attribute 'z'Subclassing a slotted class without defining __slots__ = () in the child silently re-enables __dict__ on every child instance, negating the memory savings.
Explain Python's late-binding closure behavior inside loops and how to avoid the classic loop-variable capture bug.
Senior Engineering Answer
Python closures capture variables by lexical cell reference, not by the value held at function definition time. When lambdas or nested functions inside a for-loop reference the loop variable, they all share the same enclosing variable cell, which holds the final iteration value once the loop finishes. You fix this by binding the current value eagerly via a default parameter (lambda i=i: i), wrapping creation in a helper function, or using functools.partial.
# Buggy: all callbacks return 4 funcs_bug = [lambda: i for i in range(5)] # Fixed with default argument capture funcs_ok = [lambda i=i: i for i in range(5)] print([fn() for fn in funcs_ok]) # [0, 1, 2, 3, 4] # Alternative with functools.partial from functools import partial funcs_partial = [partial(lambda x: x, i) for i in range(5)]
This trap commonly surfaces when registering callbacks in asyncio tasks, Tkinter/Qt buttons, or pytest parametrization loops where execution happens after the loop completes.
How does the Global Interpreter Lock (GIL) work in CPython, and how do threading, multiprocessing, asyncio, and PEP 703 free-threaded builds differ?
Senior Engineering Answer
The GIL is a mutex in standard CPython that ensures only one OS thread executes Python bytecode at a time, protecting non-thread-safe reference counting and internal interpreter state. Threads still release the GIL during blocking I/O syscalls and C-extension calls wrapped in Py_BEGIN_ALLOW_THREADS (like NumPy or zlib), making threading effective for I/O-bound work but serializing pure-Python CPU work. Multiprocessing bypasses the GIL via separate OS processes and memory spaces at the cost of IPC/pickling overhead, while asyncio multiplexes thousands of concurrent I/O operations on a single thread via an event loop. PEP 703 (experimental in Python 3.13t) removes the GIL in free-threaded builds using biased reference counting, mimalloc, and fine-grained object locks for true multi-core CPU threads.
import asyncio
from concurrent.futures import ProcessPoolExecutor
def cpu_heavy(n: int) -> int:
return sum(i * i for i in range(n))
async def run_hybrid() -> list[int]:
loop = asyncio.get_running_loop()
with ProcessPoolExecutor() as pool:
tasks = [loop.run_in_executor(pool, cpu_heavy, 5_000_000) for _ in range(4)]
return await asyncio.gather(*tasks)Claiming Python threads are always useless is wrong: I/O-bound libraries (requests, psycopg, boto3) release the GIL around socket waits, and CPU-bound C extensions like NumPy release it around vectorized kernels.
How does Python's descriptor protocol govern attribute lookup, and what is the difference between a data descriptor and a non-data descriptor?
Senior Engineering Answer
A descriptor is any class implementing __get__, __set__, or __delete__. Data descriptors implement __set__ or __delete__ (for example, @property); non-data descriptors implement only __get__ (for example, plain methods and @functools.cached_property). During obj.attr lookup in object.__getattribute__, Python checks in strict order: (1) data descriptors on type(obj)'s MRO, (2) obj.__dict__, (3) non-data descriptors and class attributes on type(obj)'s MRO, and finally (4) __getattr__ if nothing matched. Because non-data descriptors rank below instance __dict__, @cached_property can store its computed value directly in obj.__dict__['attr'] on first access so subsequent reads bypass the descriptor entirely.
class PositiveFloat:
def __set_name__(self, owner: type, name: str) -> None:
self.storage_name = f"_{name}"
def __get__(self, instance: object, owner: type | None = None) -> float:
if instance is None:
return self # accessed on class
return getattr(instance, self.storage_name)
def __set__(self, instance: object, value: float) -> None:
if value <= 0:
raise ValueError("must be positive")
setattr(instance, self.storage_name, float(value))
class Order:
amount = PositiveFloat()
def __init__(self, amount: float) -> None:
self.amount = amountStoring descriptor values inside a dictionary keyed by instance on the descriptor itself leaks memory unless you use WeakKeyDictionary or store a mangled attribute on the instance via __set_name__.
What are the most common production bugs in Python asyncio applications—specifically around blocking calls, fire-and-forget tasks, and cancellation?
Senior Engineering Answer
First, calling synchronous blocking I/O (requests.get, time.sleep, sync DB drivers) inside an async def coroutine stalls the entire event loop for every concurrent request; blocking work must be offloaded via asyncio.to_thread(). Second, asyncio.create_task() only keeps a weak reference to the task internally: if the caller discards the returned Task object, the garbage collector can destroy a pending task mid-execution. Third, catching bare Exception or BaseException without re-raising asyncio.CancelledError breaks structured cancellation and causes shutdown hangs; in Python 3.11+, asyncio.TaskGroup enforces structured concurrency by retaining references and cancelling sibling tasks automatically on failure.
import asyncio
background_tasks: set[asyncio.Task[None]] = set()
def spawn_safe(coro) -> None:
task = asyncio.create_task(coro)
background_tasks.add(task)
task.add_done_callback(background_tasks.discard)
async def fetch_all(urls: list[str]) -> list[str]:
async with asyncio.TaskGroup() as tg:
tasks = [tg.create_task(fetch_one(u)) for u in urls]
return [t.result() for t in tasks]Swallowing CancelledError in a broad 'except BaseException:' block leaves tasks un-cancellable and breaks asyncio.wait_for() timeouts and TaskGroup teardown.
How does CPython combine reference counting with its generational cyclic garbage collector, and when can memory still leak?
Senior Engineering Answer
CPython immediately frees objects the moment their reference count drops to zero (deterministic deallocation). Because reference counting cannot reclaim reference cycles (A -> B -> A), CPython tracks container objects in three GC generations (0, 1, 2) and periodically runs a mark-and-sweep cycle detector on container references when allocation counts cross thresholds. Memory can still leak via unintended global/module-level caches, closures or tracebacks holding frame locals, C-extension reference count bugs (missing Py_DECREF), or high-water-mark arenas that pymalloc retains from the OS.
import gc
import weakref
class Node:
def __init__(self, name: str) -> None:
self.name = name
self.parent: weakref.ReferenceType[Node] | None = None
self.children: list[Node] = []
def add_child(self, child: "Node") -> None:
child.parent = weakref.ref(self) # avoids parent<->child cycle
self.children.append(child)
print(gc.get_threshold()) # e.g. (700, 10, 10)Calling gc.collect() in a tight loop to 'save memory' pauses the interpreter unnecessarily and promotes surviving objects into Generation 2, where future scans are much more expensive.
When should you choose __init_subclass__ or class decorators over a custom metaclass, and how does C3 MRO resolution work?
Senior Engineering Answer
Metaclasses control class creation via __new__ and __init__ on type subclasses, which introduces metaclass conflicts whenever a class inherits from two bases with incompatible metaclasses (e.g., ABCMeta and a custom metaclass). Since Python 3.6, __init_subclass__ handles 90% of plugin registration, validation, and attribute injection cleanly with zero metaclass conflicts, while class decorators handle non-inherited transforms. Reserve metaclasses for altering the class namespace dictionary before class creation (__prepare__), customizing isinstance/issubclass (__instancecheck__), or wrapping class-level attribute access. Multiple inheritance method lookup follows C3 linearization, preserving local precedence order and monotonicity.
class PluginBase:
registry: dict[str, type["PluginBase"]] = {}
def __init_subclass__(cls, *, plugin_name: str, **kwargs: object) -> None:
super().__init_subclass__(**kwargs)
if plugin_name in PluginBase.registry:
raise ValueError(f"Duplicate plugin: {plugin_name}")
PluginBase.registry[plugin_name] = cls
class S3Plugin(PluginBase, plugin_name="s3"):
passOverriding __init_subclass__ without calling super().__init_subclass__(**kwargs) breaks cooperative multiple inheritance with mixins or ABCs.
How do Python's buffer protocol and memoryview enable zero-copy slicing and high-throughput binary I/O?
Senior Engineering Answer
Slicing a bytes or bytearray object normally allocates a new object and copies every byte in the slice. Types implementing the C buffer protocol (bytes, bytearray, array.array, mmap, NumPy arrays) expose their raw contiguous memory directly to memoryview without copying. Creating a memoryview slice (mv[1024:2048]) creates only a small view header pointing to the original buffer, enabling zero-copy protocol framing, socket.recv_into(), and in-place struct parsing.
import struct
def parse_frames(buf: bytearray) -> list[tuple[int, bytes]]:
view = memoryview(buf)
offset = 0
frames: list[tuple[int, bytes]] = []
while offset + 4 <= len(view):
(length,) = struct.unpack_from("!I", view, offset)
offset += 4
payload = view[offset : offset + length] # zero-copy slice
frames.append((length, bytes(payload)))
offset += length
return framesTrying to resize a bytearray while an active memoryview points to it raises BufferError ('Existing exports of data: object cannot be re-sized') until you call view.release() or exit its with-block.
How do you diagnose CPU bottlenecks and memory growth in a live production Python service without restarting it?
Senior Engineering Answer
Deterministic profilers like cProfile instrument every Python function call, distorting tight loops and adding prohibitive overhead in production. Instead, attach an out-of-process sampling profiler like py-spy or austin, which reads CPython thread state from /proc/pid/mem at 100Hz with negligible overhead and generates flame graphs including native C frames. For memory leaks, enable tracemalloc snapshots at fixed intervals to diff top allocation call sites (tracemalloc.take_snapshot().compare_to()), and inspect retained object graphs using objgraph or gc.get_referrers(). Remember that glibc/pymalloc may hold freed arenas rather than returning them to the OS, so RSS alone can overstate live Python heap.
import tracemalloc
tracemalloc.start(25)
snap1 = tracemalloc.take_snapshot()
# ... process workload ...
snap2 = tracemalloc.take_snapshot()
for stat in snap2.compare_to(snap1, "lineno")[:5]:
print(stat) # shows file:line, size diff, and object count diffRunning tracemalloc with high frame depth in hot production paths adds memory and CPU overhead per allocation; toggle it dynamically via an admin signal or diagnostic endpoint.
How do you architect a high-throughput Python data pipeline when multiprocessing pickling overhead becomes the bottleneck?
Senior Engineering Answer
Standard multiprocessing queues serialize objects with pickle and copy them through OS pipes, which often consumes more CPU than the computation itself for large arrays or DataFrames. To eliminate serialization overhead, place large buffers in multiprocessing.shared_memory (or memory-mapped Arrow/Parquet files) and pass only lightweight metadata offsets over the queue. Alternatively, offload tight numerical or parsing loops to Rust (PyO3/Maturin) or Cython extensions that release the GIL via Py_BEGIN_ALLOW_THREADS, or partition independent interpreter states using Python 3.12+ isolated subinterpreters (PEP 684) that pass immutable buffers without process fork costs.
from multiprocessing import shared_memory
import struct
# Producer allocates shared memory once; passes only shm.name to worker
shm = shared_memory.SharedMemory(create=True, size=1024)
try:
struct.pack_into("!4d", shm.buf, 0, 1.5, 2.5, 3.5, 4.5)
# Worker attaches with shared_memory.SharedMemory(name=shm.name)
vals = struct.unpack_from("!4d", shm.buf, 0)
finally:
shm.close()
shm.unlink()On Linux, multiprocessing's default 'fork' start method (deprecated for multithreaded processes in Python 3.12+) copies lock states from background threads, causing silent deadlocks; explicitly use 'spawn' or 'forkserver'.
Python Track Coverage & Difficulty Profile
16 of 16 prompts include code examplesThis Python preparation set groups 16 prompts across Junior (4), Mid (4), Senior (4), Staff (4) roles with 4 fundamental, 4 intermediate, 4 senior, 4 principal exercises tailored to Backend & Systems.
Why are mutable default arguments dangerous in Python functions, and how do you fix them idiomatically?
What is the difference between '==' and 'is' in Python, and why do small integers or short strings sometimes behave inconsistently with 'is'?
How does Python pass arguments to functions: pass-by-value or pass-by-reference?
What are the memory and control-flow differences between a list comprehension and a generator expression?
How do you write a parameterized Python decorator without losing the wrapped function's metadata or signature?
How does the Python context manager protocol work, and when should you use contextlib.ExitStack?
Frequently Asked Technical Interview Questions (Python)
Essential theoretical concepts, architecture trade-offs, and runtime design questions asked by hiring committees.
How does CPython memory management work (reference counting vs generational cyclic GC)?
What is the Global Interpreter Lock (GIL) and what are the implications of PEP 703 free-threaded Python?
How do Python generators achieve O(1) memory complexity during stream processing?
What is the difference between __new__ and __init__ in Python object instantiation?
Pair Interview Prep with Cheat Sheets & Roadmaps
Review syntax formulas on our interactive cheat sheets, test your skills in technical quizzes, and study high-scale system designs.
Want to practice other technologies?
Explore our comprehensive technical interview tracks across all core technology stacks.