Key takeaways
- At 5 years, interviewers test judgement: which concurrency model, which data structure, how you debug, test and structure a codebase — not syntax.
- Expect deep questions on the GIL and asyncio, generators, decorators, context managers, memory management and performance.
- Prepare 2–3 production stories (an outage you fixed, a performance win, a design decision) — they decide senior offers.
After five years with Python, nobody asks you what a list comprehension is. Interviewers want to see that you understand how Python behaves under load, can choose the right tool, and can own a production service. These are the questions that actually come up, grouped the way senior interviews flow. The full Python interview questions page has 100+ more with code.
Language internals
How does Python manage memory?
CPython uses reference counting, which frees an object as soon as its count hits zero, plus a generational cyclic garbage collector for reference cycles. Small objects come from the pymalloc allocator. Memory freed by Python isn't always returned to the operating system, which is why long-running processes can look like they "leak" after a spike.
What is the difference between is and ==?
== compares values using __eq__. is compares identity — whether both names point to the same object. Use is only for singletons such as None. Small integer and string interning can make is appear to work by accident.
Explain the Python data model and some dunder methods you've implemented.
Dunder methods let your classes plug into Python's syntax: __repr__ for debugging, __eq__/__hash__ for dict keys, __len__/__iter__/__getitem__ for containers, __enter__/__exit__ for with, and __call__ for callable objects. A good answer mentions keeping __eq__ and __hash__ consistent, or using @dataclass(frozen=True).
from dataclasses import dataclass
@dataclass(frozen=True, slots=True)
class Money:
amount: int # paise / cents, avoid floats for money
currency: str
def __add__(self, other: "Money") -> "Money":
if self.currency != other.currency:
raise ValueError("currency mismatch")
return Money(self.amount + other.amount, self.currency)What are __slots__, and when do they help?
__slots__ replaces the per-instance __dict__ with fixed storage for the declared attributes. That saves memory (often 40–50% per object) and speeds up attribute access, which matters when you create millions of small objects. The trade-off is that you can't add new attributes dynamically.
Concurrency and performance
How do you choose between threading, multiprocessing and asyncio?
Decide based on the workload. I/O-bound with many connections → asyncio. I/O-bound using blocking libraries → a thread pool. CPU-bound pure Python → processes, or native code (NumPy, Cython, Rust extensions). Mention the GIL, and that the free-threaded CPython build (3.13+) exists but isn't yet the default in most production stacks.
A Celery or RQ worker is slow. How do you investigate?
Measure where the time goes: per-task latency metrics, py-spy dump / py-spy top on the live worker, database query logs (look for N+1 queries), and external API timings. Fixes often include batching database calls, adding indexes, caching, raising concurrency for I/O-bound tasks, or splitting CPU-heavy tasks into a separate queue with process-based workers.
What is the difference between a generator and an iterator?
An iterator is any object with __iter__ and __next__. A generator is a convenient way to create an iterator — a function using yield — which keeps its local state between values. Generators enable lazy pipelines over huge data, and yield from delegates to sub-generators.
How do you speed up a hot loop in Python?
Profile first. Then: move work out of the loop, use built-ins and comprehensions, use sets and dicts for lookups, vectorise with NumPy or pandas, cache pure functions with lru_cache, and only then reach for Cython, Numba or a Rust/C extension.
Code quality and architecture
How do you structure a large Python codebase?
Use a src/ layout with clear domain packages, dependency direction from the outside in (API → services → domain → infrastructure adapters), configuration through environment variables validated at startup, type hints checked by mypy or pyright in CI, and ruff for linting and formatting. Keep framework code (Django/FastAPI) thin, and keep business logic in plain, testable Python.
How do you test Python code effectively?
Use pytest with fixtures and parametrisation, unit tests for pure logic, integration tests against real dependencies (Testcontainers for Postgres and Redis), unittest.mock / pytest-mock only at boundaries, property-based tests with Hypothesis for tricky logic, and coverage as a guide rather than a target.
import pytest
@pytest.mark.parametrize("raw, expected", [("10", 10), (" 7 ", 7), ("x", None)])
def test_parse_qty(raw, expected):
assert parse_qty(raw) == expectedHow do you manage dependencies and packaging in 2026?
Use pyproject.toml as the single configuration file, a lockfile for reproducible installs (uv, Poetry or pip-tools), separate dev and prod dependency groups, pinned versions in applications (but ranges in libraries), and automated update PRs plus vulnerability scanning (pip-audit).
What are type hints good for, and what are Protocols?
Type hints let static checkers catch bugs before runtime, document intent, and power editor autocompletion. A Protocol defines structural ("duck") typing: any class with the right methods matches, with no inheritance needed — ideal for dependency injection and test fakes.
from typing import Protocol
class Notifier(Protocol):
def send(self, to: str, msg: str) -> None: ...
def alert_on_failure(n: Notifier, email: str) -> None:
n.send(email, "Job failed")Production scenarios
Your FastAPI service's p95 latency doubled after a release. What do you do?
Compare the release diff; check the dashboards (latency by endpoint, database query time, error rate, CPU, event-loop lag); look at traces for the slow endpoints. Common culprits are a blocking call inside an async def handler, a new N+1 query, a missing index, a synchronous HTTP client, or a reduced worker count. Roll back first if users are affected, then fix it with a regression test and an alert.
How would you design a rate-limited client for a third-party API?
Wrap the API in one client class with: a token-bucket rate limiter (shared through Redis if there are multiple workers), retries with exponential backoff and jitter on 429/5xx, timeouts on every call, a circuit breaker, idempotency keys for writes, and structured logging and metrics per endpoint.
Final preparation checklist
- Re-read the advanced and scenario sections of the Python interview questions page
- Write a decorator, a context manager, a generator pipeline and an async fetcher from memory
- Prepare three STAR stories with numbers (latency cut, cost saved, incidents reduced)
- Do one timed DSA problem a day in Python (DSA questions)
- Take the Python quiz to find weak spots