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.

  1. Most asked Explain generators in Python.

    Generators produce values lazily, one at a time, using yield or generator expressions.

  2. Most asked Explain decorators in Python.

    A decorator is a callable that takes a function or class and returns a modified or wrapped object.

  3. Most asked Explain context managers in Python.

    Context managers define setup and cleanup around a block, usually through the with statement.

  4. 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.

  5. 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.

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

  7. Most asked Explain LEGB scoping in Python.

    LEGB is Python's name lookup order: Local, Enclosing, Global, then Built-in scope.

  8. 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.

  9. Most asked Explain list/dict/set comprehensions in Python.

    Comprehensions are concise expressions for building lists, dictionaries, and sets from iterables.

  10. Most asked Explain dataclasses in Python.

    dataclasses generate common boilerplate for classes that primarily store data.

  11. 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.

  12. 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 (_),…

  13. 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…

  14. 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.

  15. 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.

  16. Python packaging: virtualenv why?

    Virtual environments isolate project dependencies so packages and versions do not conflict across projects or with the system Python.

  17. 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.

  18. Backend Python interview: explain migrations.

    Database migrations are versioned changes that evolve schema and sometimes data safely across environments.

  19. 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),…

  20. Explain typing / type hints in Python.

    Type hints annotate expected types for tools and readers; Python does not enforce them at runtime by default.

  21. Explain exceptions hierarchy in Python.

    Python exceptions inherit from BaseException, while normal application errors should inherit from Exception.

  22. Python packaging: dependency pinning?

    Dependency pinning fixes package versions so builds are reproducible and upgrades are intentional.

  23. 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.

  24. Backend Python interview: explain connection pooling.

    Connection pooling reuses database connections instead of opening a new connection for every request.

  25. Backend Python interview: explain caching strategies.

    Caching stores expensive or frequently used results closer to the caller to reduce latency and load.

  26. 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.

  27. 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.

  28. 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.

  29. Backend Python interview: explain observability.

    Observability is the ability to understand system behavior from emitted signals: logs, metrics, traces, and events.

  30. 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.

  31. 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.…

  32. 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.

  33. Explain slots in Python.

    slots restricts instance attributes and can reduce per-instance memory by avoiding a normal dict.

  34. Explain ABC / Protocol in Python.

    An ABC defines nominal abstract interfaces through inheritance, while Protocol supports structural typing based on available methods and attributes.

  35. Explain property / descriptor in Python.

    property is a built-in descriptor that exposes method-backed access through attribute syntax.

  36. Python packaging: semantic versioning?

    Semantic versioning communicates compatibility using MAJOR.MINOR.PATCH: breaking changes, backward-compatible features, and backward-compatible fixes.

  37. Python packaging: editable installs?

    Editable installs make a project importable from its source directory so code changes are visible without reinstalling the package.

  38. Python packaging: entry points / scripts?

    Entry points define installable command-line scripts or plugin hooks for a Python package.

  39. 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.

  40. 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…

  41. 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…

  42. 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…

  43. 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…

  44. 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…

  45. 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…

  46. Python packaging: namespace packages?

    Namespace packages allow multiple distributions to contribute modules under the same top-level package name.

  47. How does Python's garbage collection work?

    Python uses reference counting plus a generational garbage collector for cyclic references.

Was this page helpful?

Report a mistake