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. 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 gc module only exists to find cycles that refcounting can't.

  2. 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. 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 or weakref.finalize for cleanup.

  4. 4. When is weakref the right tool?

    Correct answer: Caches or observers that shouldn't keep objects alive

    A weak reference doesn't raise the refcount. WeakValueDictionary entries vanish once nothing else holds the object.

  5. 5. What are immortal objects in CPython 3.12+?

    Correct answer: Objects like None whose refcount is never changed or freed

    PEP 683 skips refcount updates for singletons and some interned objects. It avoids cache-line contention and helps free-threading and subinterpreters.

  6. 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 dict

    property is a data descriptor, so it can't be shadowed by an instance attribute. Plain functions are non-data descriptors.

  7. 7. How do plain functions become bound methods?

    Correct answer: Functions are descriptors: __get__ binds them to the instance on access

    obj.f calls Class.__dict__["f"].__get__(obj, Class), which returns a bound method. staticmethod and classmethod customize __get__.

  8. 8. What is the difference between __getattr__ and __getattribute__?

    Correct answer: __getattribute__ runs on every lookup, __getattr__ only when normal lookup fails

    Overriding __getattribute__ is easy to get wrong (infinite recursion) and slows every access. __getattr__ is the safer fallback hook.

  9. 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. 10. What is a metaclass?

    Correct answer: The class of a class, controlling how classes are created

    type is the default metaclass. ORMs and frameworks used metaclasses for registration, but simpler hooks now cover most of those cases.

  11. 11. Which hook often replaces a metaclass for registering subclasses?

    Correct answer: __init_subclass__ on the base class

    It runs whenever a subclass is created and can take keyword arguments. It's simpler and composes better than custom metaclasses.

  12. 12. When do you need to override __new__ instead of __init__?

    Correct answer: Subclassing immutable types like int, or caching instances

    Immutable values are fixed when the object is created, so __init__ is too late. __new__ also fits caching or singletons.

  13. 13. Which side effect does __slots__ have beyond saving memory?

    Correct answer: Instances lose __dict__ and __weakref__ unless you list them

    Without __weakref__ in slots, weak references fail. A subclass without its own __slots__ gets a __dict__ back.

  14. 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. 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. 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. 17. On a free-threaded build, does counter += 1 from 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. 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. 19. Why is the fork start 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 forkserver the default on Linux; macOS uses spawn.

  20. 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. 21. What happens when an asyncio task is cancelled?

    Correct answer: CancelledError is raised at its current await

    finally blocks and async with exits run. Swallowing CancelledError breaks timeouts and TaskGroups, so re-raise it.

  22. 22. What does asyncio.TaskGroup add over gather?

    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 with block. Failures are raised as an ExceptionGroup.

  23. 23. How do you handle errors from an ExceptionGroup by type?

    Correct answer: With except* clauses, each matching part of the group

    except* ValueError handles the ValueError parts, and unmatched exceptions are re-raised. Several except* clauses can run.

  24. 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. 25. How do you limit an asyncio crawler to 10 concurrent requests?

    Correct answer: Acquire an asyncio.Semaphore(10) around each request

    Starting thousands of requests at once can exhaust sockets or get you rate-limited. A semaphore adds backpressure.

  26. 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 def doesn't make it non-blocking.

  27. 27. Why are contextvars used instead of threading.local in 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. 28. How can you find what blocks the event loop?

    Correct answer: Enable asyncio debug mode, which logs slow callbacks

    With PYTHONASYNCIODEBUG=1 or asyncio.run(debug=True), steps longer than slow_callback_duration are logged.

  29. 29. A service's memory grows steadily. Which tool shows where Python allocates it?

    Correct answer: tracemalloc snapshots compared over time

    tracemalloc records allocation tracebacks. Comparing two snapshots shows which lines keep growing.

  30. 30. Why is @lru_cache on an instance method a memory risk?

    Correct answer: The cache keeps self alive, so instances are never freed

    The cache is on the class-level function and holds strong references to every self it saw. Use cached_property or a per-instance cache.

  31. 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 cProfile trace every call and slow the program down.

  32. 32. What happens when a list's append needs 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. 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; use hashlib for stable hashes.

  34. 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. 35. What does typing.ParamSpec let 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. ParamSpec keeps the signature.

  36. 36. What does PEP 695 syntax def first[T](items: list[T]) -> T: replace?

    Correct answer: Declaring a module-level T = TypeVar("T") first

    Since 3.12 type parameters are declared inline for functions and classes, and type Alias = ... declares type aliases.

  37. 37. What is @typing.overload for?

    Correct answer: Describing different return types for different argument types

    The overload signatures are for the type checker only. One real implementation without @overload must follow them.

  38. 38. What does typing.Self express as a return type?

    Correct answer: The type of the actual class, including subclasses

    A builder method returning Self keeps the subclass type for chained calls. Before 3.11 this needed a bound TypeVar.

  39. 39. What does @runtime_checkable on a Protocol allow?

    Correct answer: Using it with isinstance, which checks method names only

    The check only looks at attribute presence, not signatures. It's also much slower than a normal isinstance.

  40. 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. annotationlib reads them in different formats.

  41. 41. What do template strings (t"...", PEP 750) return?

    Correct answer: A Template with the static parts and values kept separate

    Added in 3.14, they let libraries process interpolations safely, for example escaping HTML or building parametrized SQL.

  42. 42. Why is pickle.loads on 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. 43. Why avoid subprocess.run(f"convert {name}", shell=True)?

    Correct answer: A crafted name can inject shell commands

    Pass a list like ["convert", name] without a shell, so the argument is never parsed as shell syntax.

  44. 44. Which module should generate password reset tokens?

    Correct answer: secrets

    random is predictable once enough output is seen. secrets.token_urlsafe() uses the OS's secure random source. uuid1 leaks time and host data.

  45. 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. 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. 47. What does python -X importtime app.py help 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. 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. 49. How should a library tell users that a function will be removed?

    Correct answer: Emit DeprecationWarning for a while, then remove it

    Pass stacklevel=2 so the warning points at the caller's line. Since 3.13, @warnings.deprecated also informs type checkers.

  50. 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. 51. Why does case RED: in a match not compare with a constant RED?

    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. 52. What changed about functools.cached_property in 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. 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. 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. 55. How do you prevent two requests from updating the same Django row with a lost update?

    Correct answer: select_for_update() inside transaction.atomic()

    Row locks make the second transaction wait. Alternatives are F() expressions for atomic updates or optimistic locking with a version field.

  56. 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_commit sends the task only after a successful commit.

  57. 57. Why should Celery tasks be idempotent?

    Correct answer: Retries and redelivery can run a task more than once

    With acks_late or worker crashes, a task can be redelivered. Use unique keys or status checks so repeats do no harm.

  58. 58. When does an async Django view not help?

    Correct answer: When it mostly calls the sync ORM via sync_to_async

    Each sync call is handed to a thread, adding overhead. Async views pay off with many concurrent outbound I/O calls.

  59. 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. 60. Why use create_autospec or autospec=True when mocking?

    Correct answer: The mock rejects calls that don't match the real signature

    A plain Mock accepts any call and attribute, so tests pass even after the real API changes.

  61. 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. 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 obj to the function adds a temporary reference. For immortal objects, the result is a huge fixed value.

  63. 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.interpreters to use them from Python.

  64. 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. 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. 66. A hot loop calls obj.method millions 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. 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. 68. Why does timeit turn 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. 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 RuntimeError on size changes.

  70. 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.run cancels remaining tasks on exit, but in-flight work like open DB transactions needs explicit shutdown with timeouts.

  71. 71. What does asyncio.timeout(5) do around a block?

    Correct answer: Cancels the block after 5 seconds and raises TimeoutError

    Added in 3.11, it replaces many wait_for uses and can be rescheduled. Code inside must not swallow CancelledError.

  72. 72. Why can't you use the ORM from an async Django view directly?

    Correct answer: Most ORM calls are sync and raise SynchronousOnlyOperation

    Use the async QuerySet methods like aget and acount, or sync_to_async for sync code. Under the hood many still use a thread.

  73. 73. What does uv mainly 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. 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. 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.