Python Interview Questions, Advanced: GIL, Class Hooks, Memory (30 questions)
30 advanced Python interview questions for senior developers with model answers: the GIL, asyncio, threads and processes, descriptors, metaclasses, CPython internals, memory and performance.
Take this exam on Brainbotox, with marking →
Question 1
Q1. The GIL.
(a) What is the Global Interpreter Lock in CPython, and why does it exist?
(b) You have two jobs. Job A downloads 500 web pages. Job B resizes 500 large images in pure Python. For each, say whether threads make it faster, and which tool you would choose.
(c) Does the GIL make your own multi-threaded code thread-safe?
Model answer
(a) The GIL is a lock inside the standard CPython interpreter that lets only one thread execute Python bytecode at a time, even on a machine with many cores. It exists because CPython manages memory with reference counting, and the counts are not thread-safe. One global lock protects them cheaply and keeps single-threaded code and C extensions simple and fast.
(b) Two jobs
- Job A, downloads (I/O-bound): threads help a lot. A thread waiting on the network releases the GIL, so the others run meanwhile. Use
ThreadPoolExecutor, orasynciowith an async HTTP client, which handles thousands of connections in one thread. - Job B, image maths in pure Python (CPU-bound): threads do not help. The threads take turns holding the GIL, so the total time is the same or slightly worse. Use
ProcessPoolExecutorormultiprocessing: each process has its own interpreter and its own GIL, so all cores work. The cost is start-up time and copying data between processes.
from concurrent.futures import ProcessPoolExecutor
with ProcessPoolExecutor() as pool:
results = list(pool.map(resize, paths))(c) No. The GIL protects the interpreter's own state, not your data. A thread can be switched out between any two bytecodes, so counter += 1 (load, add, store) can still lose updates. Shared state still needs a threading.Lock or a queue.Queue.
Revise: Advanced Python: Internals, Concurrency, Metaclasses, Performance
Question 2
Q2. Class creation hooks. You are writing a plugin system. Every subclass of Plugin must be added automatically to a registry under its name, with no decorator and no manual call:
class CsvExport(Plugin, name="csv"): ...
class PdfExport(Plugin, name="pdf"): ...
Plugin.registry # {"csv": CsvExport, "pdf": PdfExport}(a) Implement Plugin without writing a metaclass.
(b) What is a metaclass, and when would you really need one here?
Model answer
(a) With __init_subclass__
class Plugin:
registry = {}
def __init_subclass__(cls, /, name=None, **kwargs):
super().__init_subclass__(**kwargs)
if name is None:
raise TypeError(f"{cls.__name__} needs a name")
if name in Plugin.registry:
raise ValueError(f"duplicate plugin: {name}")
cls.name = name
Plugin.registry[name] = cls- Python calls
__init_subclass__on the parent each time a subclass is defined, at the end of theclassstatement. - Keyword arguments in the class header (
name="csv") are passed to it. super().__init_subclass__(**kwargs)keeps it working with multiple inheritance.
(b) Metaclasses
A class is itself an object, and a metaclass is the class of a class. The default one is type: the statement class A: ... ends up calling type("A", bases, namespace). A custom metaclass (class Meta(type)) can change how classes are built by overriding __new__, __init__, __call__ or __prepare__.
You need one only for what __init_subclass__ and class decorators cannot do, for example:
- changing the namespace before the class body runs (
__prepare__), asenum.Enumdoes; - changing what happens when the class is called to create an instance (
__call__), for example to enforce a singleton; - adding behaviour to the class object itself, such as making
len(Plugin)or"csv" in Pluginwork.
Revise: Advanced Python: Internals, Concurrency, Metaclasses, Performance
Question 3
Q3. Memory management.
class Node:
def __init__(self):
self.other = None
a, b = Node(), Node()
a.other = b
b.other = a
del a, b(a) Are the two objects freed immediately after del? Explain how CPython frees memory in general and what happens in this case.
(b) How would you redesign this so the objects are freed at once?
(c) A program creates ten million small Point objects. What does adding __slots__ = ("x", "y") change?
Model answer
(a) Not immediately.
- CPython's main mechanism is reference counting: each object stores how many references point to it, and is freed the instant the count reaches zero.
del a, bremoves the two names, but each node is still referenced by the other's.other. Both counts stay at 1: a reference cycle.- A second mechanism handles this: the cyclic garbage collector (module
gc). It runs from time to time, finds groups of objects that are only reachable from each other, and frees them. It is generational: young objects are examined more often.
So the nodes are freed later, at the next collection that covers them, not at the del.
(b) Break the cycle with a weak reference. A weak reference does not increase the count.
import weakref
class Node:
def __init__(self):
self.other = None # strong
self._back = None # weak
def link_back(self, node):
self._back = weakref.ref(node)
@property
def back(self):
return self._back() if self._back else NoneThe typical design: a parent holds its children strongly, a child points to its parent weakly. self._back() returns the object, or None if it has already been freed.
(c) __slots__
- Normally each instance carries its own
__dict__to hold attributes. With slots there is no per-instance dict: the attributes are stored in fixed positions in the object. - Memory per object drops sharply, often by half or more, which matters at ten million objects.
- Attribute access is slightly faster.
- Trade-offs: no new attributes can be added at run time, no weak references unless
"__weakref__"is listed, and every class in the inheritance chain must define slots to keep the benefit.
tracemalloc or sys.getsizeof before deciding, and consider @dataclass(slots=True) or a NumPy array for this much numeric data.Revise: Advanced Python: Internals, Concurrency, Metaclasses, Performance
Question 4
Q4. The event loop. How does asyncio run many coroutines in a single thread? What happens at an await?
Model answer
asyncio uses cooperative multitasking. One thread runs an event loop, which keeps a queue of tasks that are ready to run and a list of things being waited for (sockets, timers).
- A coroutine runs without interruption until it reaches an
awaiton something that is not ready. - At that point it is suspended, with its local variables kept, and control returns to the loop.
- The loop runs the next ready task. When nothing is ready, it asks the operating system (through
select,epollorkqueue) which sockets or timers have become ready, and wakes the tasks waiting on them.
So concurrency comes from interleaving at await points, not from parallel execution. Only one coroutine runs at any instant.
Consequences:
- It suits I/O-bound work with many connections: thousands of tasks cost little, since a suspended task is a small object, not a thread.
- It does nothing for CPU-bound work, which still occupies the single thread.
- Code between two
awaits cannot be interrupted by another task, so many updates of shared state need no lock. A lock is needed only when an invariant must hold across anawait. - One task that never awaits, or calls a blocking function, freezes every other task.
Question 5
Q5. Blocking the loop. This server handles requests one at a time and becomes unresponsive under load. Find the two problems and fix them.
import time, requests
async def handle(url):
time.sleep(1)
resp = requests.get(url)
return resp.text
Model answer
Both calls are blocking. They do not return control to the event loop, so while one request sleeps or waits on the network, no other task can run. Marking the function async changes nothing: there is no await inside.
time.sleep(1)blocks the thread for a second.requests.getis a synchronous HTTP client: it blocks until the response has arrived.
Fix: use the awaitable equivalents.
import asyncio, httpx
async def handle(client: httpx.AsyncClient, url: str) -> str:
await asyncio.sleep(1)
resp = await client.get(url)
return resp.textWhen no async version of a library exists, run the blocking call in a worker thread so the loop stays free:
text = await asyncio.to_thread(legacy_blocking_call, url)For heavy CPU work, a thread does not help because of the GIL. Use a process pool:
loop = asyncio.get_running_loop()
with ProcessPoolExecutor() as pool:
result = await loop.run_in_executor(pool, crunch, data)How to find such problems: run with debug mode (asyncio.run(main(), debug=True) or PYTHONASYNCIODEBUG=1), which logs any step that holds the loop for more than 100 ms.
Question 6
Q6. Running tasks together. Compare asyncio.gather and asyncio.TaskGroup when one of three tasks raises an exception. Why must you keep a reference to a task created with create_task?
Model answer
asyncio.gather(a(), b(), c())
- Runs the three concurrently and returns their results in order.
- If one raises, the exception is propagated to the caller immediately, but the other tasks keep running in the background, unsupervised.
- With
return_exceptions=True, nothing is raised: exceptions are returned in the result list, to be checked by hand.
asyncio.TaskGroup (Python 3.11+)
async with asyncio.TaskGroup() as tg:
t1 = tg.create_task(a())
t2 = tg.create_task(b())
t3 = tg.create_task(c())
# here all three are finished
print(t1.result())- If one task fails, the others are cancelled, the block waits for them to finish, and the errors are raised together as an
ExceptionGroup, handled withexcept*. - No task can outlive the
async withblock. This is structured concurrency.
Prefer TaskGroup in new code: no orphaned tasks and no lost errors.
Keeping a reference: the event loop holds only a weak reference to a task. A task created with asyncio.create_task(...) and not stored anywhere can be garbage collected before it finishes, and silently disappear.
background = set()
task = asyncio.create_task(job())
background.add(task)
task.add_done_callback(background.discard)
Question 7
Q7. A forgotten await. What does this program print?
import asyncio
async def fetch():
return 42
async def main():
x = fetch()
print(x)
asyncio.run(main())
Model answer
It prints something like <coroutine object fetch at 0x...>, followed by a warning: RuntimeWarning: coroutine 'fetch' was never awaited.
Calling an async def function does not run it. It only creates a coroutine object. The body runs when the coroutine is awaited or wrapped in a task.
x = await fetch() # 42This is a common and dangerous bug because nothing fails:
- The work is silently skipped. A forgotten
awaitondb.save(...)means the data is never written. - A coroutine object is truthy, so
if is_admin(user):withoutawaitis always true.
How to catch it:
- A type checker reports using a
Coroutinewhere a value is expected. - Linters have rules for unawaited coroutines.
- Treat the warning as an error in tests:
python -W erroror the pytest option-W error::RuntimeWarning.
Related distinction:
await coro()runs it and waits for the result, one after the other.asyncio.create_task(coro())schedules it to run concurrently and returns at once. Await the task later to get the result.
Question 8
Q8. Threads and shared state. Four threads run work(). Is the final value guaranteed to be 400,000? Explain, and fix it.
counter = 0
def work():
global counter
for _ in range(100_000):
counter += 1
Model answer
Not guaranteed. counter += 1 is not atomic. It is several bytecode steps: load counter, add 1, store the result. The interpreter can switch threads between any two of them.
If thread A loads 10, then thread B loads 10, both add 1 and both store 11: one increment is lost.
The GIL does not help. It ensures only one thread runs bytecode at a time. It does not make a sequence of bytecodes atomic. Whether you observe the loss depends on the Python version and on timing, which is exactly why this kind of bug is dangerous: it may pass in tests and fail in production.
Fix with a lock:
import threading
counter = 0
lock = threading.Lock()
def work():
global counter
for _ in range(100_000):
with lock:
counter += 1Better designs that avoid sharing:
- Each thread counts in a local variable and returns its total. Sum the results at the end.
- Pass work and results through a
queue.Queue, which is thread-safe.
Individual operations on built-in types, such as list.append or dict[key] = value, are thread-safe in CPython, but any read-then-write sequence across them is not. With the free-threaded build, relying on such details becomes even less wise.
Question 9
Q9. Processes. What must be true of the function and arguments passed to multiprocessing? What are the start methods, and why does this code fail on Windows and macOS?
from multiprocessing import Pool
pool = Pool(4)
print(pool.map(lambda x: x * x, range(10)))
Model answer
Processes do not share memory. Arguments and results travel between them by pickling: they are serialised, sent through a pipe, and rebuilt on the other side.
So everything passed must be picklable: a function defined at the top level of a module, and data made of ordinary types. Lambdas, nested functions, open files, sockets and locks are not. Large arguments are copied, which can cost more than the work saved.
Start methods
fork(Unix): the child is a copy of the parent's memory. Fast, but unsafe if the parent has threads or holds locks.spawn: a fresh interpreter is started and imports the main module. Slower, but clean. Default on Windows and macOS.forkserver: a clean server process forks the workers. Default on Linux since Python 3.14; before that, Linux usedfork.
Two failures in the code:
- The lambda cannot be pickled.
- There is no main guard. With
spawn, each child imports the main module, which runsPool(4)again, which starts more children. Python detects this and raises aRuntimeError.
from multiprocessing import Pool
def square(x):
return x * x
if __name__ == "__main__":
with Pool(4) as pool:
print(pool.map(square, range(10)))
Question 10
Q10. concurrent.futures. You need to download 100 URLs with 10 threads, process each result as soon as it is ready, and not lose errors. Write it, and explain the difference between executor.map and as_completed.
Model answer
from concurrent.futures import ThreadPoolExecutor, as_completed
def fetch(url):
... # returns the body, may raise
with ThreadPoolExecutor(max_workers=10) as pool:
futures = {pool.submit(fetch, url): url for url in urls}
for fut in as_completed(futures):
url = futures[fut]
try:
body = fut.result()
except Exception as exc:
print(f"{url} failed: {exc}")
else:
print(f"{url}: {len(body)} bytes")submitschedules one call and returns aFutureat once.- A
Futureholds the eventual result or exception.result()re-raises the exception of the worker in the calling thread. If you never call it, the error is silently lost. - The
withblock waits for all work to finish and shuts the pool down.
executor.map(fetch, urls) returns results in the order of the inputs. A slow first URL delays everything behind it, and the first exception stops the iteration, so later results are not reached.
as_completed(futures) yields each future as soon as it finishes, in any order, and lets you handle each error separately.
The same interface works with ProcessPoolExecutor for CPU-bound work: change one line. Pass a timeout to result() or as_completed() to avoid waiting for ever.
Question 11
Q11. Descriptors. What is a descriptor? Write one, Positive, that makes sure an attribute is always greater than zero, usable for several fields of a class.
Model answer
A descriptor is an object that defines __get__, __set__ or __delete__, and is stored as a class attribute. When the attribute is accessed through an instance, Python calls those methods instead of reading the value directly.
class Positive:
def __set_name__(self, owner, name):
self.name = "_" + name # where to store the value
def __get__(self, obj, objtype=None):
if obj is None:
return self # accessed on the class
return getattr(obj, self.name)
def __set__(self, obj, value):
if value <= 0:
raise ValueError(f"{self.name[1:]} must be positive")
setattr(obj, self.name, value)
class Product:
price = Positive()
stock = Positive()
def __init__(self, price, stock):
self.price = price # goes through __set__
self.stock = stock
Product(10, -1) # ValueError: stock must be positive__set_name__is called when the class is created, and tells the descriptor which attribute name it was assigned to.- The value is kept on the instance, so each object has its own.
This is the mechanism behind much of Python: property, classmethod, staticmethod, bound methods (a function is a descriptor whose __get__ binds self), __slots__, and the fields of ORMs such as Django and SQLAlchemy.
A descriptor replaces a repeated @property: write the validation once, reuse it for any number of fields.
Question 12
Q12. Attribute lookup. In what order does Python look for obj.x? What is the difference between __getattr__ and __getattribute__?
Model answer
For obj.x, the default lookup (object.__getattribute__) proceeds in this order:
- Data descriptor on the class (or a base class in the MRO): an attribute that defines
__set__or__delete__, such as aproperty. It wins over everything. - The instance's own
__dict__. - Non-data descriptor or plain attribute on the class: methods (functions define only
__get__) and ordinary class attributes. - If nothing was found:
__getattr__, if the class defines it. OtherwiseAttributeError.
This explains two facts:
- You cannot shadow a
propertyby assigning to the instance: the property is a data descriptor, step 1. - You can shadow a method with an instance attribute: methods are non-data descriptors, step 3, after the instance dict.
The two hooks
__getattr__(self, name)is called only when normal lookup fails. It is the safe one. Use it for proxies, lazy attributes, or delegating to a wrapped object.__getattribute__(self, name)is called for every attribute access. It is powerful and risky: accessingself.anythinginside it recurses for ever. Callsuper().__getattribute__(name)instead. It also slows down all attribute access.
class Proxy:
def __init__(self, target):
self._target = target
def __getattr__(self, name):
return getattr(self._target, name)
Question 13
Q13. __new__ and __init__. What is the difference between __new__ and __init__? When do you need to override __new__? Write an UpperStr subclass of str whose value is always upper case.
Model answer
Creating an object with Cls(args) is two steps:
__new__(cls, ...)creates the object and returns it. It is a static method that receives the class.__init__(self, ...)initialises the object that already exists. It returns nothing.
__init__ is called only if __new__ returned an instance of cls.
Almost all classes only need __init__. Override __new__ when you must control the creation itself:
- Subclassing an immutable type (
str,int,tuple,frozenset). The value is fixed at creation, so by the time__init__runs it is too late to change it. - Returning an existing object: a singleton, a cache of instances, interning.
- Returning an instance of a different class, as a factory.
class UpperStr(str):
def __new__(cls, value):
return super().__new__(cls, value.upper())
s = UpperStr("hello")
print(s) # HELLO
print(isinstance(s, str)) # TrueTrying this in __init__ cannot work: a str has no way to be modified afterwards.
Note that string methods return plain str: s + "x" is a str, not an UpperStr. Subclassing built-ins is rarely the best design. A wrapper class or a validation function is usually simpler.
Question 14
Q14. Cooperative inheritance. This mixin-based class fails with a TypeError. Why? Rewrite the classes so that any combination works.
class Base:
def __init__(self, name):
self.name = name
class TimestampMixin:
def __init__(self, created):
self.created = created
class User(TimestampMixin, Base):
def __init__(self, name, created):
super().__init__(name, created)
Model answer
The MRO of User is User, TimestampMixin, Base, object. super().__init__(name, created) calls TimestampMixin.__init__, which accepts one argument and receives two: TypeError.
Even with matching arguments, TimestampMixin.__init__ does not call super().__init__(), so Base.__init__ would never run and name would not be set.
For multiple inheritance to work, every class must cooperate:
- take its own arguments by keyword;
- accept
**kwargsfor arguments meant for other classes; - always call
super().__init__(**kwargs)to pass them along the MRO.
class Base:
def __init__(self, *, name, **kwargs):
super().__init__(**kwargs)
self.name = name
class TimestampMixin:
def __init__(self, *, created, **kwargs):
super().__init__(**kwargs)
self.created = created
class User(TimestampMixin, Base):
pass
u = User(name="Ada", created="2026-01-01")Each class takes what it needs and forwards the rest. By the time the chain reaches object, kwargs is empty. An unknown keyword produces a clear error there.
Guidelines for mixins: they add one focused behaviour, hold little or no state, are listed before the main base class, and never assume which class comes next. When the interaction gets complicated, prefer composition: give the class an object that does the job.
Question 15
Q15. Advanced generators. What does yield from do? What does send() do? Write a generator averager() that receives numbers with send and yields the running average.
Model answer
yield from iterable delegates to another iterable or generator. It yields every value from it, and also forwards send(), throw() and close() to the inner generator, and returns its return value.
def flatten(items):
for x in items:
if isinstance(x, list):
yield from flatten(x) # recursive delegation
else:
yield x
list(flatten([1, [2, [3, 4]], 5])) # [1, 2, 3, 4, 5]gen.send(value) resumes the generator and makes the paused yield expression evaluate to value. So a generator can receive data as well as produce it: a coroutine in the original sense.
def averager():
total = 0.0
count = 0
average = None
while True:
value = yield average # send() delivers value here
total += value
count += 1
average = total / count
avg = averager()
next(avg) # prime it: run to the first yield
avg.send(10) # 10.0
avg.send(20) # 15.0
avg.send(30) # 20.0- The generator must be primed with
next()(orsend(None)) before the first realsend, to advance it to the firstyield. gen.close()raisesGeneratorExitat the pausedyield, sotry/finallyblocks inside run their clean-up.gen.throw(exc)raises an exception inside it.
This machinery is what async/await was built on. In new code, use async def for concurrency and keep generators for producing sequences.
Question 16
Q16. More context managers. (a) What does returning True from __exit__ do? (b) You must open a number of files that is only known at run time and make sure all are closed. How? (c) What is async with?
Model answer
(a) __exit__(self, exc_type, exc, tb) receives the exception raised in the block, or three Nones. Returning a true value suppresses the exception: execution continues after the with block as if nothing happened. Returning False or None lets it propagate.
from contextlib import suppress
with suppress(FileNotFoundError):
os.remove("temp.txt") # ignore if missingUse it deliberately and narrowly. A context manager that swallows every exception hides bugs.
(b) contextlib.ExitStack manages a dynamic number of context managers and unwinds them in reverse order.
from contextlib import ExitStack
with ExitStack() as stack:
files = [stack.enter_context(open(p)) for p in paths]
process(files)
# every file is closed here, even if one open() failed halfwayIt can also register plain callbacks: stack.callback(cleanup, arg).
(c) async with is for resources whose set-up or clean-up must await, such as a network connection or a database transaction. The object defines __aenter__ and __aexit__, which are coroutines.
async with pool.acquire() as conn:
async with conn.transaction():
await conn.execute(...)The generator form exists too: @contextlib.asynccontextmanager on an async def with a single yield. AsyncExitStack is the async counterpart of ExitStack.
Question 17
Q17. A decorator with arguments. Write @retry(times=3, delay=0.5): it calls the function again if it raises, up to times attempts, waiting delay seconds between attempts, and re-raises the last error.
Model answer
import functools
import time
def retry(times=3, delay=0.5, exceptions=(Exception,)):
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 # out of attempts
time.sleep(delay)
return wrapper
return decorator
@retry(times=3, delay=0.5, exceptions=(ConnectionError,))
def fetch(url):
...There are three levels of function:
retry(times, delay)receives the settings and returns the real decorator.decorator(func)receives the function and returns its replacement.wrapper(*args, **kwargs)runs on every call.
That is because @retry(times=3) is evaluated first: it means fetch = retry(times=3)(fetch).
Details that matter:
- A bare
raisere-raises the current exception with its original traceback. functools.wrapskeeps the name, docstring and signature information offetch.- Retry only on specific exceptions. Retrying on everything would also repeat a
TypeErrorcaused by a bug.
In production you would also want increasing delays with some randomness (exponential backoff with jitter), a log line per attempt, and retries only for operations that are safe to repeat. An async function needs its own version, with await func(...) and await asyncio.sleep(delay).
Question 18
Q18. functools pitfalls. What is the problem with using @lru_cache on a method, as below? What are cached_property, partial and singledispatch for?
class Report:
def __init__(self, rows):
self.rows = rows
@functools.lru_cache(maxsize=None)
def total(self):
return sum(r.amount for r in self.rows)
Model answer
The cache belongs to the function, which lives on the class, so there is one cache for all instances. The key includes self.
- Memory leak: the cache holds a strong reference to every
selfit has seen. Those instances can never be garbage collected, along with theirrows, for as long as the class exists. selfmust be hashable, and a class that defines__eq__without__hash__is not.- The cached value is not refreshed if
self.rowschanges.
For a value computed once per instance, use cached_property:
class Report:
def __init__(self, rows):
self.rows = rows
@functools.cached_property
def total(self):
return sum(r.amount for r in self.rows)It computes on first access and stores the result in the instance's own __dict__. The value disappears with the instance. To recompute, delete it: del report.total.
The others:
partial(func, *args, **kwargs)returns a new callable with some arguments already filled in:int_from_bin = partial(int, base=2). Useful for callbacks.singledispatchturns a function into one that chooses its implementation by the type of its first argument, registered with@func.register. It replaces a chain ofisinstancechecks and lets other modules add cases.
@functools.singledispatch
def show(x):
return str(x)
@show.register
def _(x: list):
return ", ".join(map(show, x))
Question 19
Q19. Advanced typing. Explain what each of these is for, with a short example: TypeVar (generics), Protocol, TypedDict, Literal, and ParamSpec.
Model answer
Generics link the types of inputs and outputs. Without them, the function would return Any or a too-wide type.
def first[T](items: list[T]) -> T: # Python 3.12 syntax
return items[0]
# before 3.12
from typing import TypeVar
T = TypeVar("T")
def first(items: list[T]) -> T: ...Protocol: structural typing. Any class with the right methods matches, with no inheritance.
class Closeable(Protocol):
def close(self) -> None: ...TypedDict: a dict with known keys and a type per key. For JSON-like data that stays a plain dict at run time.
class Movie(TypedDict):
title: str
year: intLiteral: only specific values are allowed. The checker rejects any other.
def open_file(mode: Literal["r", "w", "a"]) -> None: ...ParamSpec: captures the whole parameter list of a callable, so a decorator keeps the signature of the function it wraps.
from typing import Callable, ParamSpec, TypeVar
P = ParamSpec("P")
R = TypeVar("R")
def logged(func: Callable[P, R]) -> Callable[P, R]:
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
print(func.__name__)
return func(*args, **kwargs)
return wrapperWithout ParamSpec, every decorated function would appear to accept any arguments, and the checker would stop finding wrong calls.
Also worth knowing: @overload for functions whose return type depends on the arguments, Self for methods that return their own type, and Final for constants.
Question 20
Q20. How CPython runs code. What happens between python script.py and your code executing? What are .pyc files, and how do you inspect bytecode?
Model answer
- The source is parsed into an abstract syntax tree (AST).
- The AST is compiled to bytecode: instructions for a stack-based virtual machine. One code object per module, function and class body.
- The interpreter loop executes the bytecode, one instruction at a time.
So Python is compiled, to bytecode, and that bytecode is interpreted. It is not compiled to machine code ahead of time.
.pyc files in __pycache__ are the cached bytecode of imported modules. On the next run Python skips steps 1 and 2 if the source has not changed. This makes start-up faster. It does not make the code run faster. The script you run directly is not cached.
Inspecting bytecode:
import dis
def add(a, b):
return a + b
dis.dis(add)
# LOAD_FAST a
# LOAD_FAST b
# BINARY_OP +
# RETURN_VALUEReading it explains real behaviour: why counter += 1 is not atomic (separate load, add and store instructions), and why local variables are faster than globals (LOAD_FAST is an array index, LOAD_GLOBAL is a dictionary lookup).
Recent changes:
- Python 3.11 added a specialising adaptive interpreter: hot bytecode is rewritten in place into versions specialised for the types actually seen. It made typical code noticeably faster.
- Python 3.13 added an experimental JIT compiler, off by default.
Other implementations differ: PyPy has a tracing JIT and can be many times faster on pure Python loops.
Question 21
Q21. Dict internals. How is a dict implemented in CPython? Why must keys be hashable, why is lookup O(1), and is the order of keys guaranteed?
Model answer
A dict is a hash table with open addressing.
hash(key)gives an integer. Some of its bits select a slot in a table.- If the slot is empty, the key is absent. If it holds an entry, Python compares the stored hash, then the key with
==. - If it is a different key (a collision), Python probes other slots in a fixed pseudo-random sequence.
The table is kept at most about two-thirds full and is resized when it fills up, so probe sequences stay short. That gives O(1) average lookup, insertion and deletion. The worst case, with many colliding keys, is O(n).
Hashable keys: the key's hash decides where it is stored. If the hash could change after insertion, the entry would be looked for in the wrong slot and never found. So keys must have a hash that stays constant and is consistent with ==. Immutable built-ins qualify. Lists, dicts and sets do not.
Order: since Python 3.7 it is a language guarantee that a dict keeps insertion order. The implementation (the "compact dict" of 3.6) stores entries in a dense array in insertion order, with a separate small index table of positions. That layout also uses less memory.
Other points:
- String hashes are randomised per process (
PYTHONHASHSEED), to prevent attacks that craft colliding keys. Sohash("abc")differs between runs. - Changing a dict's size while iterating over it raises
RuntimeError. - A
setis the same structure without values, but does not guarantee order.
Question 22
Q22. List internals. How is a list stored? Give the cost of append, insert(0, x), pop(), pop(0) and x in lst, and say what to use for a queue.
Model answer
A list is a dynamic array of pointers to objects, in one contiguous block. It is not a linked list. Indexing lst[i] is O(1).
The array is over-allocated: it has more room than its current length. When it is full, a larger block is allocated (roughly 12% bigger, plus a little) and the pointers are copied.
| Operation | Cost | Why |
|---|---|---|
append(x) | O(1) amortised | usually free space is available; an occasional resize is O(n) |
pop() | O(1) | removes the last item |
insert(0, x) | O(n) | every item moves one place right |
pop(0) | O(n) | every item moves one place left |
x in lst | O(n) | compares item by item |
lst[i], len(lst) | O(1) | |
slice lst[a:b] | O(b - a) | copies the pointers |
For a queue, use collections.deque: append and popleft are both O(1). Using a list as a FIFO queue with pop(0) makes a loop quadratic.
Memory: the list holds 8 bytes per item for the pointer, and each item is a separate object. A list of a million ints uses tens of megabytes. For large numeric data, array.array or a NumPy array stores the raw values contiguously, using far less memory and allowing vectorised operations.
A tuple is the same layout without over-allocation, since it cannot grow.
Question 23
Q23. Identity surprises. What does each line print in CPython, and what general rule follows?
a = 256
b = 256
print(a is b)
c = 1000
d = 1000
print(c is d)
s = "hello"
t = "hel" + "lo"
print(s is t)
Model answer
a is b: True. CPython pre-creates the integers from -5 to 256 and reuses them, because they are used so often.c is d: it depends. Typed line by line at the interactive prompt, it is False: two separate objects. In a script, or on one line, it is often True, because the compiler stores the constant 1000 once per code object.s is t: usually True. The compiler folds"hel" + "lo"into the constant"hello", and short identifier-like strings are interned (stored once). A string built at run time, such as"".join(["hel", "lo"]), is generally a different object.
All of this is implementation detail. It varies between CPython versions, between the prompt and a script, and between interpreters such as PyPy.
The rule: compare values with ==. Use is only for singletons: None, True, False, NotImplemented, sentinel objects and enum members.
_MISSING = object() # a private sentinel
def get(key, default=_MISSING):
if default is _MISSING: # identity is exactly right here
...A sentinel is useful when None is a valid value and you need to tell "not provided" apart from "provided as None".
sys.intern(s) forces a string to be interned. It can save memory and speed up comparisons when the same strings occur millions of times, for example as dict keys parsed from a large file.
Question 24
Q24. Profiling and optimising. A Python batch job takes 40 minutes. Describe your method for making it faster. Which tools do you use, and which kinds of change usually bring the biggest gains?
Model answer
1. Measure before changing anything. Intuition about where time goes is usually wrong.
python -m cProfile -o out.prof job.py, then view withpstatsorsnakeviz: time per function and number of calls.py-spy top --pid Norpy-spy record: a sampling profiler that attaches to a running process with very low overhead, and produces a flame graph.line_profiler: time per line of one suspect function.timeit: to compare two small snippets reliably.
2. Fix in order of expected gain.
- Algorithm and data structure. A list searched inside a loop becomes a set or a dict. A nested loop becomes a lookup. This is where 100 times faster comes from.
- I/O. One query per row becomes one query for all rows (the N+1 problem). Batch the writes. Run independent network calls concurrently.
- Push loops into C. Use built-ins (
sum,sorted,str.join, comprehensions), and vectorise numeric work with NumPy or pandas instead of looping over values in Python. - Avoid repeated work. Cache results, compute invariants once outside the loop.
- Parallelism. Processes for CPU-bound work, threads or asyncio for I/O.
- Compiled code for the remaining hot spot: Cython, Numba, a Rust or C extension. Or try PyPy.
3. Measure again after each change, on realistic data, and keep the tests passing.
Micro-optimisations, such as binding a method to a local variable, give a few percent. Do them last, if at all, and only in the measured hot loop.
Question 25
Q25. Memory leaks. A long-running Python service uses more and more memory. Python has garbage collection, so how can it leak? How do you find the cause?
Model answer
In Python a "leak" is almost always objects that are still referenced but no longer needed. The collector cannot free what is reachable.
Usual causes:
- A module-level dict or list used as a cache that only grows.
@lru_cache(maxsize=None), orlru_cacheon a method, which keeps every argument and instance alive.- Lists of callbacks or listeners that are never removed.
- Closures, tasks and stored exceptions holding large objects. A saved traceback references every frame, and so all their local variables.
- Class attributes that accumulate data across instances.
- C extensions that leak outside Python's control.
Also possible: no leak at all. CPython does not always return freed memory to the operating system, because of fragmentation, so the process size stays at its peak.
Finding it
import tracemalloc
tracemalloc.start(25) # keep 25 frames of traceback
snap1 = tracemalloc.take_snapshot()
# ... let the service run ...
snap2 = tracemalloc.take_snapshot()
for stat in snap2.compare_to(snap1, "lineno")[:10]:
print(stat) # lines whose allocations grew mosttracemallocshows where the growing memory was allocated.gc.get_objects()with a count per type shows what is accumulating.objgraph.show_backrefs(obj)shows who is holding it.memrayprofiles a running process, including native allocations.
Fixes: bound every cache (a size limit or a time to live), use weakref.WeakValueDictionary for caches that should not keep objects alive, and remove listeners when their owner goes away.
Question 26
Q26. Pickle. How does pickle serialise an object, and why must you never unpickle data from an untrusted source? What do you use instead?
Model answer
pickle turns a Python object graph into bytes and back. It handles almost any object, including instances of your own classes and shared or circular references.
For an instance, it normally stores a reference to the class by name, plus the contents of __dict__. Loading imports the class and rebuilds the instance. A class can customise this with __getstate__/__setstate__ or __reduce__.
The danger: a pickle is not just data. It is a small program for a stack machine that tells the unpickler which callables to import and call, with which arguments. __reduce__ may return any callable.
class Evil:
def __reduce__(self):
return (os.system, ("rm -rf ~",))
pickle.loads(pickle.dumps(Evil())) # runs the commandSo pickle.loads on attacker-controlled bytes is arbitrary code execution. No option makes it safe. This includes data from a network client, an upload, a cookie, a shared cache or queue that others can write to, and machine-learning model files from the internet.
Use instead:
jsonfor data exchanged with anything outside your process. It can only produce dicts, lists, strings, numbers, booleans andNone.- A schema-based format (Protocol Buffers, MessagePack, Avro) for speed or compactness, with validation by a library such as
pydantic. - For model weights, formats designed to hold only data, such as
safetensors.
Pickle remains fine between processes you control, which is how multiprocessing uses it. Other limits: pickles are tied to your class definitions, so renaming a class breaks old data, and they are not readable from other languages.
Question 27
Q27. The import system. How does Python find a module? Explain sys.path, sys.modules, the role of __init__.py, and the difference between absolute and relative imports.
Model answer
For import pkg.mod:
- Check the cache
sys.modules. If the module is there, use it. - Otherwise ask each finder in
sys.meta_path: built-in modules, frozen modules, then the path-based finder. - The path finder searches the directories in
sys.path, in order: the script's directory (or the current directory), thenPYTHONPATH, then the standard library, thensite-packages. - The finder returns a spec, and a loader creates the module object, registers it in
sys.modules, and executes its code.
The first matching name wins. A file named random.py or email.py in your project shadows the standard library module, a frequent source of confusing errors.
__init__.py marks a directory as a regular package and runs when the package is first imported. It is the place to define the package's public interface. A directory without it can still be imported as a namespace package, which can be spread over several directories, but tools often expect the file, so include it.
Absolute and relative
from myapp.db.models import User # absolute: from a root on sys.path
from .models import User # relative: same package
from ..utils import slugify # relative: parent packageRelative imports work only inside a package. They fail in a file run directly as a script ("attempted relative import with no known parent package"). Run it as a module instead: python -m myapp.db.tool.
Also: importlib.import_module(name) imports by a name computed at run time, for plugins. Moving a heavy import inside the function that needs it speeds up start-up.
Question 28
Q28. Patching in tests. The test below still calls the real network. Why? Fix it.
# app/service.py
from app.http import get_json
def user_name(user_id):
return get_json(f"/users/{user_id}")["name"]
# tests/test_service.py
from unittest.mock import patch
from app.service import user_name
@patch("app.http.get_json")
def test_user_name(mock_get):
mock_get.return_value = {"name": "Ada"}
assert user_name(1) == "Ada"
Model answer
patch replaces a name in a namespace for the duration of the test. Here it replaces the name get_json in the module app.http.
But app/service.py did from app.http import get_json. That statement copied a reference to the original function into the namespace of app.service at import time. user_name looks up get_json in its own module, finds the original, and calls the network. The patched name in app.http is never consulted.
The rule: patch where the object is looked up, not where it is defined.
@patch("app.service.get_json")
def test_user_name(mock_get):
mock_get.return_value = {"name": "Ada"}
assert user_name(1) == "Ada"
mock_get.assert_called_once_with("/users/1")If the code had written import app.http and called app.http.get_json(...), then patching app.http.get_json would be correct, because the lookup happens through that module at call time.
Good practice with mocks:
- Use
autospec=True(orcreate_autospec), so the mock has the real function's signature. A call with wrong arguments then fails, instead of being silently accepted. - Assert on how the mock was called, not only on the return value.
- Patch at the boundary of your system (HTTP, database, clock), not your own internal functions. Tests that mock everything keep passing when the code is broken.
- Often better than patching: pass the dependency as a parameter, and give the test a fake.
Question 29
Q29. Speeding up CPU-bound code. A pure Python function that processes a large array of numbers is the bottleneck. List the options for making it faster, from least to most effort, with the trade-offs.
Model answer
- Better algorithm, built-ins. First check the complexity. Then move the loop into C-implemented functions:
sum,min,sorted,itertools, comprehensions. Free and often enough. - Vectorise with NumPy. Replace the Python loop with array operations, which run in compiled code over contiguous memory. Commonly 10 to 100 times faster. Trade-off: the logic must be expressible as whole-array operations, and temporary arrays use memory.
# loop: one Python-level operation per element
total = sum(x * x for x in values)
# vectorised: one call, loop in C
arr = np.asarray(values)
total = (arr * arr).sum()- Numba. Add
@njitto a numeric function. It is compiled to machine code on first call. Excellent for explicit loops over arrays. Trade-off: supports only a subset of Python and NumPy, and has a compilation delay. - Multiprocessing. Split the data and use all cores with
ProcessPoolExecutor. Gain is at most the number of cores, minus the cost of pickling data to and from the workers. Use shared memory for large arrays. - Cython, or an extension in C or Rust (with PyO3). Full control and the best speed. Trade-off: a build step, another language, and a boundary to maintain.
- Another interpreter. PyPy's JIT speeds up pure Python loops a lot, with little code change. Trade-off: weaker compatibility with C extensions.
Threads do not help for pure Python CPU work under the GIL, unless the work happens inside a library that releases it, as NumPy does, or you run the free-threaded build.
Whatever the option: profile first, optimise only the hot function, and keep a simple reference implementation to test the fast one against.
Question 30
Q30. Implement an LRU cache. Write a class LRUCache(capacity) with get(key) and put(key, value), both in O(1). When the cache is full, put evicts the least recently used key. Explain your choice of data structure.
Model answer
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity: int):
if capacity <= 0:
raise ValueError("capacity must be positive")
self.capacity = capacity
self._data = OrderedDict()
def get(self, key, default=None):
if key not in self._data:
return default
self._data.move_to_end(key) # now the most recent
return self._data[key]
def put(self, key, value):
if key in self._data:
self._data.move_to_end(key)
self._data[key] = value
if len(self._data) > self.capacity:
self._data.popitem(last=False) # evict the oldestThe cache needs two things at once, each in O(1):
- find a key: a hash table;
- know the order of use, move a key to the "most recent" end, and remove from the "oldest" end: a doubly linked list.
OrderedDict is exactly that combination: a dict plus a doubly linked list of its keys. move_to_end and popitem(last=False) are both O(1).
A plain dict keeps insertion order too, but has no O(1) way to move a key to the end other than deleting and reinserting it, and no direct way to pop the first item.
If asked to do it without OrderedDict: keep a dict from key to node, and a doubly linked list of nodes with dummy head and tail. get unlinks the node and relinks it at the tail. put adds at the tail and, when over capacity, removes the node after the head and deletes its key from the dict.
Points an interviewer looks for:
- updating an existing key counts as a use;
- a missing key must be distinguishable from a stored
None(use a sentinel default, or raiseKeyError); - it is not thread-safe: wrap the methods in a
threading.Lockif shared; - for caching function results, the standard library already has
functools.lru_cache.