Python developer interview questions, from internals to Django and FastAPI

Python developer interview questions test how well you understand the language under the surface: mutability and references, how dicts and lists behave, iterators and generators, decorators and context managers, the GIL and when to reach for threads, processes or asyncio, type hints, and packaging. Web roles add Django, Flask or FastAPI, and almost every loop includes a live coding problem plus pytest-style testing questions. Good answers show you write idiomatic Python and know where its performance traps are.

By Published 8 min read

Where Python developers work, and what interviewers probe

Python shows up in web backends, internal tools, data pipelines, test automation, DevOps scripting and machine learning services. A Python developer job usually means one of the first three: building APIs with Django, Flask or FastAPI, writing ETL jobs and integrations, or automating work other teams do by hand. Because the language is easy to start with, interviewers spend their time on the parts that separate a script writer from an engineer: the object model, memory and performance, concurrency, testing and maintainable package structure.

  • Pythonic code: comprehensions, unpacking, the standard library and clear names instead of ported Java or C habits.
  • A mental model of the runtime: names bound to objects, reference counting, and what is slow in CPython.
  • Concurrency judgment: the right tool for I/O-heavy versus CPU-heavy work.
  • Production habits: type hints, linting, tests, logging and reproducible environments.
  • Framework fluency: request handling, ORM queries and background tasks in at least one stack.

The usual shape of a Python interview process

  1. Intro callThe Python versions and frameworks you use, the size of the projects, and whether you lean toward web, data or automation work.
  2. Language screenA quick run through core Python: data types, mutability, scope, generators and decorators. Sometimes you predict the output of short snippets.
  3. Live codingOne or two problems in a shared editor or notebook. Clean, readable Python matters as much as getting the answer.
  4. Practical or take-homeA small API, a data-processing script with tests, or a debugging exercise in an existing codebase.
  5. Design and team fitService or data pipeline design for senior roles, plus behavioral questions about collaboration and incidents.

Language fundamentals and internals

Core Python questions
QuestionWhat it testsWhat a strong answer shows
A function with a default argument of [] returns different results on repeat calls. Why?Mutable defaultsDefaults are evaluated once at definition time, so the same list is reused; use None and create the list inside the function
What is the difference between is and ==?Identity and equalityis compares object identity, == calls __eq__; use is only for None and other singletons, since small-int and string caching make other cases misleading
Lists versus tuples: when does the difference matter?MutabilityTuples are immutable and hashable if their items are, so they work as dict keys and signal fixed records; lists are for collections that change
How does a dict look up a key so quickly?Hash tablesKeys are hashed into a compact table with open addressing; average lookups are constant time, and insertion order is kept since 3.7
What does copy.copy do that copy.deepcopy does not?ReferencesA shallow copy makes a new container holding the same inner objects; a deep copy recursively copies those too, which matters for nested lists and dicts
Explain how Python resolves a variable name.ScopeLocal, enclosing, global, then built-in; nonlocal and global let you assign to outer names
Lambdas created in a loop all return the last value. What is going on?ClosuresClosures capture variables, not values, so they read the loop variable after the loop ends; bind it with a default argument or functools.partial
How does CPython free memory?Memory managementReference counting frees most objects immediately, and a cyclic garbage collector finds reference cycles; __del__ timing is not something to rely on
Core Python questions. Scroll sideways on a small screen.

Object-oriented Python

  • What are dunder methods, and which have you implemented? Special methods like __repr__, __eq__, __hash__, __len__, __iter__ and __enter__ let your classes work with built-in syntax. Implement __repr__ on almost everything.
  • How does the method resolution order work with multiple inheritance? C3 linearization produces one order, visible in ClassName.__mro__, and super() follows it, which is why cooperative classes call super() consistently.
  • classmethod, staticmethod or a plain function? classmethod for alternative constructors that need the class, staticmethod for helpers grouped with the class, and a module-level function when there is no real link to the class.
  • When are dataclasses the right choice, and what about attrs or Pydantic? Dataclasses for plain records with less boilerplate, with frozen=True for immutability. Pydantic when you need validation and parsing of external input.
  • What does @property give you? Computed attributes and validation behind ordinary attribute syntax, so you can start with a public field and add logic later without changing callers.
  • What are __slots__ for? They replace the per-instance dict with fixed attribute storage, saving memory when you create millions of small objects, at the cost of flexibility.

Data structures and the standard library

Choosing the right container
QuestionWhat it testsWhat a strong answer shows
You need a queue with fast appends and pops at both ends. What do you use?collections.dequedeque, since popping from the front of a list is linear time
Count word frequencies in a file in a few lines.CounterCounter over a generator of lowercased words, then most_common(n)
How would you keep the top k items from a large stream?heapqA min-heap of size k with heappushpop, giving n log k time and little memory
Group records by a key without checking whether the key exists.defaultdictdefaultdict(list) and append, or setdefault for one-off cases
How do you search a sorted list efficiently?bisectbisect_left and bisect_right for logarithmic lookups and ordered inserts
Set or list for membership checks inside a loop?ComplexityA set gives average constant-time lookups; checking membership in a list each time makes the loop quadratic
Choosing the right container. Scroll sideways on a small screen.

Iterators, generators, decorators and context managers

  • What is the iterator protocol? An iterable returns an iterator from __iter__, and the iterator returns items from __next__ until it raises StopIteration. A for loop does exactly that.
  • Why would you write a generator instead of returning a list? It yields one item at a time, so memory stays flat for large files or endless streams, and work happens only when the caller asks for the next item.
  • What does yield from do? It delegates to a sub-generator, passing values, sends and exceptions through, which keeps recursive or layered generators short.
  • Write a decorator that times a function, and explain functools.wraps. A wrapper that records time before and after the call. wraps copies the name, docstring and signature so logging, debugging and frameworks still see the original function.
  • How do you write a decorator that takes arguments? Add one more layer: a function that takes the arguments and returns the actual decorator. A retry decorator with a configurable count is a common exercise.
  • Why use a context manager, and how do you write one? Setup and cleanup that always run, even on exceptions: files, locks, transactions, temporary settings. Write a class with __enter__ and __exit__, or a generator with contextlib.contextmanager.
  • Which itertools functions do you actually use? chain, islice, groupby on sorted data, product and accumulate are common in coding rounds.
import functools
import time

def retry(times: int, delay: float = 0.5):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for attempt in range(1, times + 1):
                try:
                    return func(*args, **kwargs)
                except ConnectionError:
                    if attempt == times:
                        raise
                    time.sleep(delay * attempt)
        return wrapper
    return decorator
A retry decorator with an argument, a frequent live exercise

The GIL, concurrency and performance

Concurrency questions
QuestionWhat it testsWhat a strong answer shows
What is the GIL, and what does it stop you from doing?GILA lock that lets only one thread run Python bytecode at a time in CPython, so threads do not speed up pure-Python CPU work; I/O and many C extensions release it
You must download 500 URLs. Threads, processes or asyncio?Choosing a modelI/O-bound, so a thread pool or asyncio with an HTTP client like httpx or aiohttp; processes add overhead with no gain here
You must resize 10,000 images on an 8-core machine. What now?CPU-bound workmultiprocessing or ProcessPoolExecutor, chunked inputs, and care with what you pickle between processes
What happens if you call a blocking function inside an async def endpoint?Event loopIt blocks the event loop and stalls every other request; use an async library, or run it in a thread with asyncio.to_thread or run_in_executor
Has the GIL gone away?Current PythonRecent CPython releases offer an optional free-threaded build, but the standard build still has the GIL and many libraries assume it
A script is slow. How do you find out why?ProfilingcProfile or py-spy to find hot functions, then better algorithms or data structures first, vectorizing with NumPy, caching with lru_cache, and C extensions last
Concurrency questions. Scroll sideways on a small screen.

Typing, packaging and code quality

  • Why add type hints if Python does not enforce them at runtime? They document intent, catch bugs through mypy or Pyright before runtime, and power editor completion. Pydantic and FastAPI also use them to validate data.
  • What are Protocol and TypedDict for? Protocol describes structural interfaces, duck typing that a checker can verify. TypedDict types dicts with known keys, such as JSON payloads.
  • How do you set up a new project's environment and dependencies? A virtual environment per project, dependencies declared in pyproject.toml, a lock file from Poetry, uv or pip-tools, and the Python version pinned for CI.
  • What is the difference between a wheel and a source distribution? A wheel is a pre-built package that installs quickly without a build step; an sdist must be built on install, which matters for C extensions.
  • Which tools keep a Python codebase healthy? Ruff or Flake8 for linting, Black or Ruff for formatting, a type checker, pre-commit hooks, and pytest in CI.

Django, Flask and FastAPI questions

Web framework questions
QuestionWhat it testsWhat a strong answer shows
A Django list page runs one query per row. How do you fix it?Django ORMselect_related for foreign keys and one-to-one, prefetch_related for many-to-many and reverse relations, checked with Django Debug Toolbar or assertNumQueries
How do Django migrations work, and how do you change a big table safely?Schema changesMigrations record model changes; for large tables add nullable columns first, backfill in batches, then add constraints in a later release
What does middleware do in Django?Request pipelineHooks around every request and response for things like auth, sessions, CSRF and logging, applied in the order listed in settings
Flask app context, request context, blueprints: what are they?Flask structureContexts make current_app and request available per request; blueprints split routes into modules registered on an app factory
Why do teams pick FastAPI for new APIs?FastAPIAsync support, Pydantic validation from type hints, dependency injection and automatic OpenAPI docs
How do you run slow work outside the request?Background jobsA task queue such as Celery, RQ or Dramatiq with Redis or RabbitMQ, with retries and idempotent tasks
Web framework questions. Scroll sideways on a small screen.

Testing and coding rounds

  • Why do most teams prefer pytest to unittest? Plain assert statements with rich failure output, fixtures for setup and teardown, parametrize for table-driven tests, and a large plugin ecosystem.
  • How do you mock an external API call in a test? Patch where the name is looked up, not where it is defined, using unittest.mock.patch or pytest's monkeypatch, or use a library like responses or respx for HTTP.
  • What do you test in a FastAPI or Django endpoint? Status codes, validation errors, permission checks and side effects, using the framework's test client and a real test database where possible.
  • Typical live coding topics? String manipulation, two-sum style hash map problems, sliding windows, interval merging, tree traversal and graph search. Use the standard library well and explain complexity.
  • Senior design prompt: a pipeline that ingests files daily and loads them into a warehouse. Talk about idempotent loads, schema validation, retries, monitoring and what happens when one file is bad.

Fictional example

Answering "Tell me about a time you made Python code faster"
We had a nightly reconciliation script that matched payment records against orders, and it had grown from twenty minutes to over three hours as volume rose. I ran it under py-spy and saw almost all the time in one function that checked whether each payment ID was in a list of order IDs. That list had about a million entries, so every check scanned it. I changed the list to a set, which removed most of the time, and then replaced a row-by-row loop that built a report with a pandas merge. The run dropped to under ten minutes. I added a benchmark test with a sample data set so a future change would show up in CI if it made the script much slower again.

Python web roles overlap heavily with general backend work; see the backend developer interview guide for API and database design, and the Java developer guide if the team runs services in both languages.

Questions to ask your interviewers

  • Which Python version and framework does the team use, and how far behind the latest are you?
  • How do you manage dependencies and environments across services?
  • Do you use type checking in CI, and how strict is it?
  • What does the path from a merged pull request to production look like?

A study plan for the next two weeks

  1. Snippet drillsPredict the output of short snippets on mutability, scope, closures and default arguments, then run them to check.
  2. Write the classics by handA generator pipeline, a decorator with arguments, a context manager, a dataclass with validation, and an LRU cache with OrderedDict.
  3. Concurrency labFetch many URLs with threads and with asyncio, and do a CPU task with a process pool. Measure each and explain the results.
  4. One small serviceA FastAPI or Django app with a database, typed models, pytest tests and a background task.
  5. Timed problems and storiesDaily coding problems in Python under a timer, plus four stories: a bug, a speed-up, a disagreement and a delivery under pressure.

When you rehearse, Natively, an AI interview assistant that runs on Mac and Windows, captures a transcript of the mock interview on your machine and can offer a suggested answer while a question about generators or the GIL is being asked. It can also pick up a coding problem from a screenshot. If you upload your résumé and the job description (Pro or the free trial), suggestions lean on the projects you have actually built. The notes and transcript are kept so you can go back over the session afterward.

Questions people ask

What are the most common Python developer interview questions?

Mutable default arguments, is versus ==, lists versus tuples, how dicts work, generators and yield, decorators, context managers, the GIL and when to use threads, processes or asyncio, and how you test and package code.

What Python interview questions do experienced developers get?

Deeper questions on the object model and MRO, memory management, profiling and performance, asyncio pitfalls, typing with Protocol and generics, ORM query optimization, and a design round for a service or data pipeline.

Do Python interviews ask about Django or FastAPI?

Web roles usually do. Expect ORM performance, migrations, middleware and request handling for Django, and async endpoints, Pydantic models and dependency injection for FastAPI.

How should freshers prepare for a Python interview?

Master the core data types, comprehensions, functions and scope, basic OOP, exceptions and file handling, then practice easy and medium coding problems in Python while explaining your approach aloud.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP