Interview Q&A · questions with model answers
Python Developer Interview Questions
Part of the study plan for: Full Stack Engineer · Native AI Engineer · Forward Deployed Engineer (FDE) · Machine Learning Engineer · Data Engineer
Ordered by how often they're asked. Most-asked answers are free to read in full; members see every answer and can rate their confidence on each.
-
Most asked Explain generators in Python.
Generators produce values lazily, one at a time, using yield or generator expressions.
-
Most asked Explain decorators in Python.
A decorator is a callable that takes a function or class and returns a modified or wrapped object.
-
Most asked Explain context managers in Python.
Context managers define setup and cleanup around a block, usually through the with statement.
-
Most asked Explain GIL in Python.
In CPython, the Global Interpreter Lock allows only one thread at a time to execute Python bytecode in a process.
-
Most asked Backend Python interview: explain N+1 queries.
N+1 queries happen when code loads one set of rows and then issues an extra query for each row, causing query count to grow with result size.
-
Most asked Backend Python interview: explain SQL injection prevention.
Prevent SQL injection by using parameterized queries or ORM query builders instead of string-concatenating user input into SQL.
-
Most asked Explain LEGB scoping in Python.
LEGB is Python's name lookup order: Local, Enclosing, Global, then Built-in scope.
-
Most asked Explain *args and **kwargs in Python.
*args captures extra positional arguments as a tuple, and kwargs captures extra keyword arguments as a dictionary.
-
Most asked Explain list/dict/set comprehensions in Python.
Comprehensions are concise expressions for building lists, dictionaries, and sets from iterables.
-
Most asked Explain dataclasses in Python.
dataclasses generate common boilerplate for classes that primarily store data.
-
Most asked Explain dunder methods in Python.
Dunder methods are special methods like len, iter, and eq that let objects participate in Python language protocols.
-
Most asked Explain structural pattern matching (`match`/`case`).
Python 3.10's match statement compares a subject against patterns: literals, captures, sequences, mappings, class patterns with attributes, OR patterns (|), guards (if), and wildcards (_),…
-
Most asked Walk through the request/response lifecycle in Django, and explain why middleware order matters.
The WSGI or ASGI handler builds an HttpRequest; it passes down through MIDDLEWARE in order; the URL resolver picks the view; process_view hooks run; the view returns a response (process_exception on…
-
Most asked Explain MRO / C3 in Python.
MRO is the method resolution order Python uses to search classes in inheritance hierarchies, computed with the C3 linearization algorithm.
-
Explain __name__ == '__main__' in Python.
The name == 'main' guard runs code only when a file is executed as a script, not when it is imported as a module.
-
Python packaging: virtualenv why?
Virtual environments isolate project dependencies so packages and versions do not conflict across projects or with the system Python.
-
Backend Python interview: explain REST API design.
Good REST API design models resources with predictable URLs, HTTP methods, status codes, representations, validation, and error contracts.
-
Backend Python interview: explain migrations.
Database migrations are versioned changes that evolve schema and sometimes data safely across environments.
-
How does asyncio work internally: event loop, coroutines, tasks and futures?
A coroutine is created by calling an async def function and runs only when awaited or wrapped in a Task. The event loop schedules Tasks, running each until it awaits something not ready (a Future),…
-
Explain typing / type hints in Python.
Type hints annotate expected types for tools and readers; Python does not enforce them at runtime by default.
-
Explain exceptions hierarchy in Python.
Python exceptions inherit from BaseException, while normal application errors should inherit from Exception.
-
Python packaging: dependency pinning?
Dependency pinning fixes package versions so builds are reproducible and upgrades are intentional.
-
Backend Python interview: explain FastAPI / Starlette.
FastAPI is a high-level API framework built on Starlette for ASGI routing and Pydantic for validation and serialization.
-
Backend Python interview: explain connection pooling.
Connection pooling reuses database connections instead of opening a new connection for every request.
-
Backend Python interview: explain caching strategies.
Caching stores expensive or frequently used results closer to the caller to reduce latency and load.
-
Backend Python interview: explain JWT pitfalls.
JWTs are signed tokens that carry claims, but common pitfalls include weak validation, long lifetimes, unsafe storage, and treating claims as always current.
-
Backend Python interview: explain idempotent APIs.
An idempotent API produces the same intended server state when the same request is repeated once or many times.
-
Backend Python interview: explain background jobs.
Background jobs move work out of the request path when it is slow, retryable, scheduled, or independent of the immediate response.
-
Backend Python interview: explain observability.
Observability is the ability to understand system behavior from emitted signals: logs, metrics, traces, and events.
-
Backend Python interview: explain 12-factor config.
12-factor config means storing environment-specific configuration outside code, usually in environment variables or managed secret/config systems.
-
How do cancellation and timeouts work in asyncio?
task.cancel() raises CancelledError inside the task at its next await; asyncio.timeout(seconds) (3.11+) or asyncio.wait_for() cancel the inner work when the deadline passes and raise TimeoutError.…
-
How does CPython manage memory?
CPython uses reference counting (objects are freed when their count hits zero) plus a generational cyclic garbage collector for reference cycles, and the pymalloc allocator for small objects.
-
Explain slots in Python.
slots restricts instance attributes and can reduce per-instance memory by avoiding a normal dict.
-
Explain ABC / Protocol in Python.
An ABC defines nominal abstract interfaces through inheritance, while Protocol supports structural typing based on available methods and attributes.
-
Explain property / descriptor in Python.
property is a built-in descriptor that exposes method-backed access through attribute syntax.
-
Python packaging: semantic versioning?
Semantic versioning communicates compatibility using MAJOR.MINOR.PATCH: breaking changes, backward-compatible features, and backward-compatible fixes.
-
Python packaging: editable installs?
Editable installs make a project importable from its source directory so code changes are visible without reinstalling the package.
-
Python packaging: entry points / scripts?
Entry points define installable command-line scripts or plugin hooks for a Python package.
-
Backend Python interview: explain rate limiting.
Rate limiting controls how many requests a client, user, IP, token, or tenant can make in a time period to protect reliability and abuse boundaries.
-
How do you handle dates and time zones correctly in Python?
Use timezone-aware datetime objects in UTC internally (datetime.now(timezone.utc)), convert to local zones with zoneinfo.ZoneInfo('Europe/Berlin') for display, and avoid naive datetimes and the…
-
How do `functools.cache`, `lru_cache` and `cached_property` work, and what are the pitfalls?
@cache (unbounded) and @lru_cache(maxsize=N) memoize function results by arguments (which must be hashable); @cached_property computes an attribute once per instance and stores it in the instance…
-
How did annotation evaluation change in Python 3.14?
With PEP 649/749, annotations are evaluated lazily (on access via annotationlib/annotations) instead of eagerly at definition time, so forward references work without quotes or from future import…
-
How do sorting, `heapq` and `bisect` help with common algorithmic tasks?
sorted()/list.sort() use Timsort (stable, O(n log n)) with key functions; heapq provides a min-heap for top-k and priority queues (nlargest, heappush); bisect does binary search and insertion in…
-
How do classic design patterns look in idiomatic Python?
Many are simplified by first-class functions and modules: Strategy becomes passing a function, Singleton becomes a module-level instance, Factory becomes a callable or class method, Observer uses…
-
How do descriptors power properties, methods and ORMs?
A descriptor is an object with get, set or delete stored on a class; attribute access on instances is routed through it. property, classmethod, staticmethod, bound methods and ORM column attributes…
-
Python packaging: namespace packages?
Namespace packages allow multiple distributions to contribute modules under the same top-level package name.
-
How does Python's garbage collection work?
Python uses reference counting plus a generational garbage collector for cyclic references.