Skip to main content
VirtualInterview.ai

Software & Engineering

Python Developer mock interview

A Python developer interview checks whether you know what the interpreter does with your code and how your web framework handles a request. Expect language questions on the screen (mutable defaults, generators, how you manage dependencies), a technical round on concurrency choices, Django or FastAPI behaviour and a coding task, and a story about a slow job you made faster.

Practising from this page puts you in a technical round for a Python Developer. When an answer stays general, the AI interviewer asks for the detail, such as how you measured the speed-up you just claimed. Somewhere after the first question, a short round gives you one coding exercise drawn from the job’s domain, and it opens in Python unless your job post or skills name another language. Every answer is scored from 0 to 100 for relevance, depth and clarity. The round report then weighs code quality (25%), problem solving (30%), technical knowledge (25%) and communication (20%).

Practice this role with an AI interviewer

Free plan: 2 interviews a month, free account, no card.

What the loop usually looks like

  1. Recruiter or technical screen (30 to 45 min). Core Python: lists versus tuples, mutable default arguments, *args and **kwargs, decorators, generators, and how you set up a project with virtual environments and pinned dependencies. One project you explain in detail.
  2. Technical round (45 to 60 min). The GIL and when threads, processes or asyncio fit; the Django or FastAPI request lifecycle; ORM query behaviour; type hints. A coding exercise in a shared editor, often parsing or aggregating data.
  3. Design and behavioural (45 to 60 min). A service or data pipeline design, then stories: a slow job you profiled, a dependency upgrade that broke production, a code review you pushed back on.

What interviewers score

  • Language semantics: objects, defaults, iteration and scope
  • Choosing threads, processes or asyncio for the actual workload
  • How Django or FastAPI runs a request, and where the database time goes
  • Measuring before optimising, with a profiler and a number

What interviewers probe at each level

Junior or fresher

Expect the classics, asked with a twist. Why does a function with L=[] as a default keep old values? What is the difference between a list comprehension and a generator expression in memory? What does a decorator return? Why use a virtual environment? The follow-up checks that you can predict output, so practise saying what a short snippet prints and why.

Mid level

The questions move to systems you have run. Which concurrency model did you use for that scraper, and why? How did you find the query that made the Django admin page slow, and did you use select_related or prefetch_related? In FastAPI, when do you write def instead of async def? Do you run mypy in CI? Bring one example per answer with a number in it.

Senior and lead

Senior rounds probe judgement and standards. How do you pin and upgrade dependencies across several services? Walk through profiling a slow batch job end to end. What would the free-threaded build change for your workloads, and what would you test first? What do you block in code review? Expect a design round and an incident told from detection to the change that stopped it recurring.

Mistakes that cost candidates this round

  • Saying "the GIL means Python can’t do concurrency", which ignores that the GIL is released during I/O.
  • Reaching for multiprocessing for an I/O-bound job, or for threads for a CPU-bound one, without saying why.
  • Calling a blocking database driver or requests inside an async def endpoint, then wondering why the whole server stalls.
  • Describing an optimisation with no measurement before or after.
  • Treating type hints as runtime validation. They are checked by a separate tool, not by the interpreter.
  • Committing the virtual environment, or copying one between machines instead of recreating it from a lock file.
  • Writing the coding exercise in silence and only testing it in your head at the end.

The GIL: how to choose threads, processes or asyncio

The Python glossary defines the global interpreter lock as the mechanism CPython uses so that only one thread executes Python bytecode at a time. It also says two things candidates forget: extension modules may release the GIL during heavy work such as compression or hashing, and the GIL is always released during I/O. That is why threads still help a program that spends its time waiting on the network or disk.

So the answer interviewers want is a choice tied to the workload. For many slow network calls, use asyncio if your libraries support await, or a thread pool if they do not. For CPU-heavy pure Python work, use processes, or move the hot loop into a library that releases the GIL. Then say the cost of each: processes copy data and take longer to start, threads share state and need locks, and asyncio needs every library in the call path to be async.

Senior candidates get asked about free threading. As of Python 3.13 the GIL can be disabled in a build configured with --disable-gil, described in PEP 703. A good answer says it is a separate build, that C extensions must support it, and that you would benchmark your real workload on it before planning around it.

Sources: Python documentation, Glossary: global interpreter lock

Django and FastAPI: what happens to a request

Django runs middleware in the order of the MIDDLEWARE setting on the way in and in reverse on the way out. The documentation compares it to an onion: if one layer returns a response without calling the next, nothing inside it, including the view, sees the request. process_view() runs just before the view, and if it returns an HttpResponse the view is skipped. Interviewers ask this to see whether you can explain why an authentication or caching middleware placed in the wrong spot broke something.

For the database, know the two tools for related objects. select_related follows foreign key and one-to-one relations with an SQL join in a single query. prefetch_related runs one extra query per relation and joins the results in Python, and it also handles many-to-many and reverse foreign keys. Name the one that fits the relation and say how you checked the query count before and after.

FastAPI questions usually come down to def versus async def. A path operation declared with plain def runs in an external threadpool, so a blocking call there does not stop the event loop. An async def function runs on the event loop itself, so it must not do blocking I/O. The same rule applies to dependencies. The documentation’s advice, if you are unsure, is plain def.

Sources: Django documentation: Middleware; Django documentation: QuerySet API reference; FastAPI documentation: Concurrency and async / await

How should I answer "how would you profile a slow job"?

Start with a number: the job takes 40 minutes and it needs to finish in 10. Then measure where the time goes before changing anything. cProfile from the standard library gives call counts and times per function. You can run it from the command line with python -m cProfile and sort the output with -s, for example by cumulative time to find the call tree that dominates. Newer Python versions also add a sampling profiler that is cheaper to run against production-like loads.

The Python docs point out that the profilers are not benchmarking tools: they add overhead to Python code but not to C functions, so use timeit for a precise comparison of two versions. A complete answer goes measure, change one thing, measure again, and usually ends somewhere outside Python, such as an unindexed query or a loop that made one HTTP call per row.

Sources: Python 3.13 documentation: The Python profilers

Packaging, typing and the questions juniors get

The tutorial’s warning about default arguments is a common screening question. A default is evaluated once, so a list default collects values across calls. The fix is a None default and a new list inside the function. Be ready to say what the snippet prints before you explain it.

On environments, the venv documentation says each environment has its own packages, isolated from the base Python, is not checked into source control, and should be deleted and recreated rather than copied or moved. Say how your team recreates one: a requirements file or a lock file, and a pinned Python version.

On typing, PEP 484 is explicit that Python stays dynamically typed, hints are optional, and no type checking happens at runtime; a separate checker such as mypy does it. If an interviewer asks whether hints validate API input, the answer is no, unless a library like Pydantic reads them and checks the data.

Sources: Python tutorial 4.9: Default argument values; Python documentation: venv; PEP 484: Type hints

How do I rehearse a Python interview here?

Use the technical round from this page and speak your answers, since delivery feedback is speech-based: speaking pace, filler words (in English answers) and pauses, measured from your spoken answer. The coding exercise opens in Python when neither your job post nor your skills name another language, and it is set in the job’s domain instead of a puzzle. The interviewer reads your code and your explanation, and nothing executes it, so say your test cases aloud: the empty input, the malformed row, the tie.

After the report, redo the answer with the lowest depth score. In Python rounds that is usually the concurrency answer that named a tool without the reason, or the performance story without a measurement.

10 python developer interview questions and model answers

1. What does this print, and why? def add(item, items=[]): items.append(item); return items. Then add(1), add(2).

Technical. What they are testing: Whether you know defaults are evaluated once.

The second call returns [1, 2], not [2]. The default list is created once, when the def statement runs, and every call that does not pass items shares it. The fix is items=None as the default and items = [] inside the function when it is None. I have seen this bug in a real codebase as a cache that never cleared, so I also check for it in code review.

2. What is the GIL, and when does it actually matter for your code?

Technical. What they are testing: Accurate understanding, not the myth that Python cannot do concurrency.

It is the lock CPython uses so only one thread runs Python bytecode at a time. It matters for CPU-bound pure Python work, where adding threads does not add speed. It matters much less for I/O-bound work, because the GIL is released while a thread waits on I/O, and some C extensions release it during heavy computation. So for a service that mostly waits on a database and other APIs, threads or asyncio are fine. For number crunching in Python loops, I would use processes or a library that does the work in C.

3. You need to call an external API for 50,000 records. How would you make it fast?

Technical. What they are testing: Picking a concurrency model and handling limits and failures.

This is I/O-bound, so I would run requests concurrently. If we already use httpx, asyncio with an async client and a semaphore to cap concurrent requests at what the API allows, maybe 20. If the client library is sync only, a ThreadPoolExecutor with the same cap. Each request gets a timeout and a retry with backoff for 429 and 5xx responses. I would write results in batches and record which IDs failed, so a rerun only does the failures. Processes would not help here, because the time is spent waiting.

4. In FastAPI, when do you declare an endpoint with def and when with async def?

Technical. What they are testing: Knowing the threadpool behaviour and the blocking-call trap.

If the endpoint calls something I have to await, like an async database driver, it is async def. If it calls blocking code, like a sync ORM or requests, it is plain def, and FastAPI runs it in a threadpool so it does not block the event loop. The mistake I have seen is async def with a blocking call inside, which freezes every other request on that worker. The same rule applies to dependencies.

5. A Django list page got slow as data grew. How do you find and fix the cause?

Technical. What they are testing: ORM query awareness and the right related-object tool.

I would count queries first, with the debug toolbar locally or a test that asserts the query count. A list that shows the author of each article usually runs one query per row. For a foreign key like author, select_related joins it into the main query. For a many-to-many like tags, prefetch_related runs one extra query and joins in Python. Then I would check the plan for the main query and add an index if the filter column has none. I would put the query-count assertion in a test so it does not come back.

6. Tell me how you profiled and sped up a slow job.

Technical. What they are testing: Measuring before optimising, with a real number.

A nightly reconciliation job had grown to 50 minutes. I ran it on a copy of the data under cProfile, sorted by cumulative time, and 70% of it was inside one function that looked up a currency rate per row. Each lookup was a database query. I loaded the rates for the day into a dict once at the start, and the job dropped to 9 minutes. The next biggest cost was building pandas frames inside a loop, which I changed to one frame at the end. I kept the timing in the job’s log so we would see if it crept back up.

7. How do you manage dependencies and environments across several Python services?

Technical. What they are testing: Reproducible builds and upgrade discipline.

Each service has its own virtual environment, never committed, recreated from a lock file in CI and in the Docker image. We pin exact versions in the lock and keep looser ranges in pyproject for direct dependencies. The Python version is pinned too. Upgrades go through a scheduled job that opens a pull request, and the test suite has to pass before anyone merges it. When a transitive dependency broke us once, the lock file let us roll back by reverting one commit.

8. Do type hints make your code safer at runtime?

Technical. What they are testing: Knowing what typing does and does not do.

Not by themselves. PEP 484 says hints are optional and nothing checks them at runtime. They help because we run mypy in CI, which catches things like passing None where a function expects a string, and because editors use them. If I need runtime checks, for example on API input, I use something that reads the hints and validates, like Pydantic models in FastAPI. I would add hints to new code and to public functions first, rather than annotate an old codebase in one go.

9. Tell me about a dependency upgrade or deploy that broke production.

Behavioral. What they are testing: Ownership and the fix that stops it recurring.

We upgraded a date library as part of a routine bump, and one service started rejecting timestamps from a partner because the parser had become stricter. Errors started within minutes. I rolled back to the previous image, which we could do in one step, and confirmed the error rate went to zero. Then I wrote a test with the partner’s exact timestamp format, fixed the parsing on our side, and redeployed. The change I pushed afterwards was contract tests with real sample payloads from each partner.

10. Write a function that reads a log file and returns the five slowest endpoints by average response time. Talk me through it.

Domain. What they are testing: Clean Python on a realistic task, plus testing instincts.

I would confirm the format first: one request per line, with the path and a duration in milliseconds. I would read the file line by line with a generator, so a large file does not load into memory, and skip lines that do not parse rather than crash, counting them. Then a dict of path to a running total and count, compute averages, and heapq.nlargest(5). Tests: an empty file, a malformed line, fewer than five endpoints, and a tie. If paths include IDs, I would ask whether to normalise /users/123 to /users/{id} first.

Frequently asked questions

What Python questions are asked in a developer interview?

Language basics (mutable defaults, generators, decorators, data types), concurrency and the GIL, a web framework such as Django or FastAPI, ORM query behaviour, packaging and virtual environments, type hints, and from mid level up, a performance story and a production incident.

Is a Python developer interview different from a data science interview?

Yes. A developer loop focuses on services, frameworks, concurrency and code quality. A data science loop leans on statistics, pandas, SQL and modelling. If the job mixes both, practise both: the data scientist and data engineer pages cover the other half.

Will the coding exercise be in Python?

Usually. Python is the fallback when neither the job post you attach nor your skills name a language, so a Python job post or a Python skill list keeps it there. If it opens in something else, switch the editor’s Language menu. The task is set in the job’s domain. The interviewer reads your code and your explanation; nothing runs it.

Can I practise a Python mock interview for free?

Yes, on the free plan: 2 interviews a month, free account, no card. A Python technical round counts as one of those interviews, and its report scores every answer.