Python Senior cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. How does CPython free most objects?
Correct answer: Reference counting frees them at once; a cyclic GC handles reference cycles
When a refcount drops to zero, the object is freed right away. The
gcmodule only exists to find cycles that refcounting can't.2. Why does the cyclic garbage collector use generations?
Correct answer: Most objects die young, so new objects are scanned more often than old ones
Scanning every container object on each pass would be slow. Survivors move to older, rarely scanned generations. 3.14 switched to an incremental collector.
3. What risk comes with defining
__del__on a class?Correct answer: It's not guaranteed to run at a predictable time, or at all at exit
Cycles delay finalization, and exceptions in
__del__are only printed. Use context managers orweakref.finalizefor cleanup.4. When is
weakrefthe right tool?Correct answer: Caches or observers that shouldn't keep objects alive
A weak reference doesn't raise the refcount.
WeakValueDictionaryentries vanish once nothing else holds the object.5. What are immortal objects in CPython 3.12+?
Correct answer: Objects like
Nonewhose refcount is never changed or freedPEP 683 skips refcount updates for singletons and some interned objects. It avoids cache-line contention and helps free-threading and subinterpreters.
6. What is the difference between a data descriptor and a non-data descriptor?
Correct answer: A data descriptor defines
__set__or__delete__and wins over the instance dictpropertyis a data descriptor, so it can't be shadowed by an instance attribute. Plain functions are non-data descriptors.7. How do plain functions become bound methods?
Correct answer: Functions are descriptors:
__get__binds them to the instance on accessobj.fcallsClass.__dict__["f"].__get__(obj, Class), which returns a bound method.staticmethodandclassmethodcustomize__get__.8. What is the difference between
__getattr__and__getattribute__?Correct answer:
__getattribute__runs on every lookup,__getattr__only when normal lookup failsOverriding
__getattribute__is easy to get wrong (infinite recursion) and slows every access.__getattr__is the safer fallback hook.9. What does
__set_name__give a descriptor?Correct answer: The owner class and attribute name it was assigned to
It's called at class creation. A validating field can store values under its own name without repeating it.
10. What is a metaclass?
Correct answer: The class of a class, controlling how classes are created
typeis the default metaclass. ORMs and frameworks used metaclasses for registration, but simpler hooks now cover most of those cases.11. Which hook often replaces a metaclass for registering subclasses?
Correct answer:
__init_subclass__on the base classIt runs whenever a subclass is created and can take keyword arguments. It's simpler and composes better than custom metaclasses.
12. When do you need to override
__new__instead of__init__?Correct answer: Subclassing immutable types like
int, or caching instancesImmutable values are fixed when the object is created, so
__init__is too late.__new__also fits caching or singletons.13. Which side effect does
__slots__have beyond saving memory?Correct answer: Instances lose
__dict__and__weakref__unless you list themWithout
__weakref__in slots, weak references fail. A subclass without its own__slots__gets a__dict__back.14. What does
dis.dis(func)show?Correct answer: The bytecode instructions CPython runs for the function
Bytecode varies between versions. It's useful to see why one form is cheaper or how specialization changed instructions.
15. What did the specializing adaptive interpreter in 3.11 change?
Correct answer: Hot bytecode is rewritten into type-specific instructions at runtime
If an addition keeps seeing ints, it's replaced by an int-specific instruction, with a fallback when types change. That brought much of 3.11's speedup.
16. What does the free-threaded CPython build (PEP 703) change?
Correct answer: The GIL can be disabled so threads run Python code in parallel
Experimental in 3.13 and officially supported in 3.14, it's a separate build. C extensions must declare support, or the GIL is turned back on.
17. On a free-threaded build, does
counter += 1from many threads stay correct?Correct answer: No, it's a read-modify-write; you still need a lock
Even with the GIL,
+=could be interrupted between read and write. Built-in containers stay internally consistent, but your logic still needs synchronization.18. Why can NumPy speed up with threads even on a GIL build?
Correct answer: Its C code releases the GIL during heavy array operations
C extensions can drop the GIL while working on raw memory, so several threads compute at once. Pure Python loops can't.
19. Why is the
forkstart method risky in a multithreaded process?Correct answer: The child copies held locks, but not the threads that would release them
A lock held by another thread at fork stays locked in the child forever, causing deadlocks. Python 3.14 made
forkserverthe default on Linux; macOS usesspawn.20. What has to be true about arguments sent to a
ProcessPoolExecutor?Correct answer: They must be picklable, since they're serialized to the worker
Lambdas and local functions aren't picklable. Large arguments also cost serialization time, which can erase the speedup.
21. What happens when an asyncio task is cancelled?
Correct answer:
CancelledErroris raised at its currentawaitfinallyblocks andasync withexits run. SwallowingCancelledErrorbreaks timeouts and TaskGroups, so re-raise it.22. What does
asyncio.TaskGroupadd overgather?Correct answer: If one task fails, the rest are cancelled and errors raised together
Added in 3.11, it's structured concurrency: no task outlives the
async withblock. Failures are raised as anExceptionGroup.23. How do you handle errors from an
ExceptionGroupby type?Correct answer: With
except*clauses, each matching part of the groupexcept* ValueErrorhandles theValueErrorparts, and unmatched exceptions are re-raised. Severalexcept*clauses can run.24. Why keep a reference to a task created with
asyncio.create_task?Correct answer: The loop holds only a weak reference, so it may be collected mid-run
Store fire-and-forget tasks in a set and remove them in a done callback, or use a TaskGroup.
25. How do you limit an asyncio crawler to 10 concurrent requests?
Correct answer: Acquire an
asyncio.Semaphore(10)around each requestStarting thousands of requests at once can exhaust sockets or get you rate-limited. A semaphore adds backpressure.
26. What is the right way to call a blocking library from async code?
Correct answer:
await asyncio.to_thread(func, *args)It runs the call in the default thread pool so the loop keeps serving others. Wrapping blocking code in
async defdoesn't make it non-blocking.27. Why are
contextvarsused instead ofthreading.localin async code?Correct answer: Each task gets its own context, while all tasks share one thread
Request IDs or the current user stored in thread-locals would leak between tasks on the same loop. Tasks copy the context when created.
28. How can you find what blocks the event loop?
Correct answer: Enable asyncio debug mode, which logs slow callbacks
With
PYTHONASYNCIODEBUG=1orasyncio.run(debug=True), steps longer thanslow_callback_durationare logged.29. A service's memory grows steadily. Which tool shows where Python allocates it?
Correct answer:
tracemallocsnapshots compared over timetracemallocrecords allocation tracebacks. Comparing two snapshots shows which lines keep growing.30. Why is
@lru_cacheon an instance method a memory risk?Correct answer: The cache keeps
selfalive, so instances are never freedThe cache is on the class-level function and holds strong references to every
selfit saw. Usecached_propertyor a per-instance cache.31. Which profiler suits a production process you can't restart?
Correct answer: A sampling profiler like py-spy that attaches to a PID
Sampling has low overhead and needs no code changes. Deterministic profilers like
cProfiletrace every call and slow the program down.32. What happens when a list's
appendneeds more capacity?Correct answer: It over-allocates, so appends are amortized O(1)
Growth is proportional, so copies are rare. Inserting at the front is still O(n) because every item shifts.
33. Why does
hash("abc")differ between runs of Python?Correct answer: String hashes are randomized to resist collision attacks
Attackers could send keys that all collide and make dicts O(n). Never persist
hash()values; usehashlibfor stable hashes.34. How are modern CPython dicts laid out?
Correct answer: A compact array in insertion order plus a hash index
The compact layout introduced in 3.6 saves memory and is why dicts keep insertion order.
35. What does
typing.ParamSpeclet a decorator express?Correct answer: That the wrapper keeps the wrapped function's parameters
Without it, decorated functions often become
Callable[..., Any]and lose type checking.ParamSpeckeeps the signature.36. What does PEP 695 syntax
def first[T](items: list[T]) -> T:replace?Correct answer: Declaring a module-level
T = TypeVar("T")firstSince 3.12 type parameters are declared inline for functions and classes, and
type Alias = ...declares type aliases.37. What is
@typing.overloadfor?Correct answer: Describing different return types for different argument types
The overload signatures are for the type checker only. One real implementation without
@overloadmust follow them.38. What does
typing.Selfexpress as a return type?Correct answer: The type of the actual class, including subclasses
A builder method returning
Selfkeeps the subclass type for chained calls. Before 3.11 this needed a bound TypeVar.39. What does
@runtime_checkableon a Protocol allow?Correct answer: Using it with
isinstance, which checks method names onlyThe check only looks at attribute presence, not signatures. It's also much slower than a normal
isinstance.40. What changes with deferred annotation evaluation in Python 3.14 (PEP 649)?
Correct answer: Annotations are evaluated lazily, so forward references work
Names used in annotations no longer need to exist at definition time, and imports used only for typing cost less.
annotationlibreads them in different formats.41. What do template strings (
t"...", PEP 750) return?Correct answer: A
Templatewith the static parts and values kept separateAdded in 3.14, they let libraries process interpolations safely, for example escaping HTML or building parametrized SQL.
42. Why is
pickle.loadson untrusted data dangerous?Correct answer: Unpickling can run arbitrary code chosen by the data's author
Pickle can call any callable while loading via
__reduce__. Use JSON or another data-only format for external input.43. Why avoid
subprocess.run(f"convert {name}", shell=True)?Correct answer: A crafted
namecan inject shell commandsPass a list like
["convert", name]without a shell, so the argument is never parsed as shell syntax.44. Which module should generate password reset tokens?
Correct answer:
secretsrandomis predictable once enough output is seen.secrets.token_urlsafe()uses the OS's secure random source.uuid1leaks time and host data.45. What is the difference between a wheel and an sdist?
Correct answer: A wheel is a built package ready to install, an sdist is source that must be built
Wheels install fast and need no compiler. Packages with C extensions publish platform-specific wheels.
46. Why shouldn't a library pin exact dependency versions like
requests==2.32.3?Correct answer: It forces that version on every app and causes conflicts
Libraries declare compatible ranges, and applications pin exact versions in a lock file.
47. What does
python -X importtime app.pyhelp with?Correct answer: Finding which imports slow down startup
Slow startup hurts CLIs and serverless functions. Common fixes are importing heavy modules lazily and removing import-time side effects.
48. Why are import-time side effects in a library a problem?
Correct answer: Importing alone may hit the network, files or config
Tests and tools import modules without wanting a DB connection. Keep work in functions or explicit setup calls.
49. How should a library tell users that a function will be removed?
Correct answer: Emit
DeprecationWarningfor a while, then remove itPass
stacklevel=2so the warning points at the caller's line. Since 3.13,@warnings.deprecatedalso informs type checkers.50. What does
__match_args__on a class enable?Correct answer: Positional patterns like
case Point(x, y):It maps positional sub-patterns to attribute names. Dataclasses generate it automatically.
51. Why does
case RED:in amatchnot compare with a constantRED?Correct answer: A bare name is a capture pattern that binds any value
Use a dotted name like
case Color.RED:for value patterns. A bare name catches everything and makes later cases unreachable.52. What changed about
functools.cached_propertyin 3.12?Correct answer: Its lock was removed, so threads may compute it twice
The old class-wide lock serialized all instances. Add your own lock if the computation must run once.
53. How do you run a FastAPI app across several CPU cores?
Correct answer: Run several worker processes, each with its own event loop
One process is limited by the GIL for Python work. Workers from Uvicorn, Gunicorn or containers spread load, with no shared memory between them.
54. Why must a DB connection pool be created after a worker process forks?
Correct answer: Inherited sockets get shared and corrupt traffic
Two processes writing to one connection mix their protocol messages. Create pools in a post-fork hook or app startup.
55. How do you prevent two requests from updating the same Django row with a lost update?
Correct answer:
select_for_update()insidetransaction.atomic()Row locks make the second transaction wait. Alternatives are
F()expressions for atomic updates or optimistic locking with a version field.56. What is the risk of sending a Celery task inside a DB transaction?
Correct answer: The worker can run before the commit and miss the new row
Django's
transaction.on_commitsends the task only after a successful commit.57. Why should Celery tasks be idempotent?
Correct answer: Retries and redelivery can run a task more than once
With
acks_lateor worker crashes, a task can be redelivered. Use unique keys or status checks so repeats do no harm.58. When does an async Django view not help?
Correct answer: When it mostly calls the sync ORM via
sync_to_asyncEach sync call is handed to a thread, adding overhead. Async views pay off with many concurrent outbound I/O calls.
59. What does property-based testing with Hypothesis add over example tests?
Correct answer: It generates many inputs and shrinks failing ones
You state a property, like "decode(encode(x)) == x", and Hypothesis looks for counterexamples.
60. Why use
create_autospecorautospec=Truewhen mocking?Correct answer: The mock rejects calls that don't match the real signature
A plain
Mockaccepts any call and attribute, so tests pass even after the real API changes.61. Tests share a module-level cache and fail only in some orders. What's the best fix?
Correct answer: Reset the shared state in a fixture for each test
Order-dependent tests hide bugs. Running in random order (pytest-randomly) helps find them.
62. What does
sys.getrefcount(obj)usually return compared to the real number of references?Correct answer: One more, because the call's argument is also a reference
Passing
objto the function adds a temporary reference. For immortal objects, the result is a huge fixed value.63. What did per-interpreter GIL (PEP 684, 3.12) enable?
Correct answer: Subinterpreters in one process each with their own GIL
Subinterpreters run in parallel but don't share objects. 3.14 added
concurrent.interpretersto use them from Python.64. What is the status of CPython's JIT compiler as of 3.13 and 3.14?
Correct answer: Experimental and off by default in standard builds
The copy-and-patch JIT can be enabled at build time or with an env var in some builds. Real-world gains are still modest.
65. What does
add_note()on an exception do?Correct answer: Attaches extra text shown in the traceback
Added in 3.11, it lets you add context, like a failing input, without wrapping the exception in a new one.
66. A hot loop calls
obj.methodmillions of times. What micro-optimization does CPython 3.11+ make less useful?Correct answer: Caching the bound method in a local variable
Specialized attribute and method loads made the old trick mostly redundant. Profile first: the real win is usually an algorithm or a vectorized library.
67. When is moving a hot path to Rust (PyO3) or Cython worth it?
Correct answer: After profiling shows a CPU-bound core that pure Python can't speed up
Most slow services wait on I/O or run N+1 queries. A native extension adds build and maintenance cost, so it fits proven CPU hot spots.
68. Why does
timeitturn off garbage collection by default?Correct answer: To make timings of small snippets more consistent
GC pauses add noise. If your code creates many cycles, include
gc.enable()in the setup for realistic results.69. Why is mutating a list while iterating over it a bug?
Correct answer: Removing items shifts indexes, so the loop skips elements
Lists don't detect changes, so the bug is silent. Iterate over a copy or build a new list. Dicts and sets do raise
RuntimeErroron size changes.70. How do you make sure all asyncio tasks finish cleanly on SIGTERM?
Correct answer: Handle the signal, cancel tasks and await them before the loop closes
asyncio.runcancels remaining tasks on exit, but in-flight work like open DB transactions needs explicit shutdown with timeouts.71. What does
asyncio.timeout(5)do around a block?Correct answer: Cancels the block after 5 seconds and raises
TimeoutErrorAdded in 3.11, it replaces many
wait_foruses and can be rescheduled. Code inside must not swallowCancelledError.72. Why can't you use the ORM from an async Django view directly?
Correct answer: Most ORM calls are sync and raise
SynchronousOnlyOperationUse the async QuerySet methods like
agetandacount, orsync_to_asyncfor sync code. Under the hood many still use a thread.73. What does
uvmainly replace in a Python workflow?Correct answer: pip, venv tools and Python version managers
uv resolves and installs packages much faster than pip, creates venvs and lock files, and can install Python versions.
74. What is the trade-off of strict mypy in an existing large codebase?
Correct answer: Better safety, but a lot of upfront work; adopt it module by module
Turning on strict mode everywhere produces thousands of errors. Enable it per module in the config and tighten new code first.
75. Why can deeply recursive code fail in Python where it works in other languages?
Correct answer: There is a recursion limit and no tail call optimization
The default limit is about 1000 frames (
sys.getrecursionlimit()). Rewrite deep recursion as a loop with an explicit stack.