GUIDE INTERVIEW QUESTIONS

Python developer interview questions

Evaluate Python candidates with role-specific questions, realistic coding exercises, and clear scoring criteria. This guide connects language fundamentals to testing, concurrency, and production engineering.

What Python interviews should actually measure

The best python developer interview questions reveal whether someone can turn requirements into reliable, maintainable software—not merely recall syntax. For hiring managers, technical leads, and interviewers in the MyDiscussions community, the challenge is selecting questions that distinguish language familiarity from engineering judgment.

A backend developer building FastAPI services needs different evidence than an automation engineer maintaining scripts or an AI engineer shipping inference pipelines. All three should understand Python’s object model, test behavior, and diagnose failures, but the depth and application differ.

Build the interview around observable job requirements. Decide which skills must be present on day one, which can be learned, and what evidence demonstrates the expected level. Then use consistent prompts and anchored scoring rather than an overall impression of “strong Python skills.”

Define the role before choosing questions

Use the actual workload to determine interview emphasis.

Role profilePrioritizeUseful exerciseAvoid overweighting
Backend Python developerHTTP behavior, SQL, concurrency, validationImplement and test an API operationAlgorithm puzzles unrelated to service work
Automation engineerFiles, subprocesses, retries, idempotencyBuild a resumable batch taskWeb-framework trivia
Data engineerIteration, schemas, memory, pipeline recoveryProcess records with bounded memoryDataFrame syntax alone
AI application engineerModel integration, evaluation, async I/O, observabilityDesign a resilient inference clientNotebook-only demonstrations
Python platform engineerPackaging, profiling, compatibility, toolingDiagnose a dependency or performance issueMemorized command-line flags

For junior candidates, look for correct fundamentals, understandable code, and productive responses to feedback. Mid-level developers should independently deliver tested changes and recognize common operational risks. Senior developers should clarify ambiguous requirements, explain trade-offs, and anticipate failure across system boundaries.

Framework experience is evidence, not a substitute for reasoning. Someone with Django experience may learn FastAPI quickly. Someone who recognizes decorators but cannot explain transactions may struggle regardless of framework familiarity.

Core Python developer interview questions

1. What happens when a function uses a mutable default argument?

Present this code:

def add_tag(tag, tags=[]): tags.append(tag); return tags

Ask candidates to predict two consecutive calls without an explicit tags argument.

A strong answer explains that the default list is created when the function definition executes and reused across calls. The usual correction uses None as the default and creates a list inside the function.

Follow up: Should the function mutate a caller-provided list? That question separates recognition of a famous pitfall from API design judgment. Either behavior can be valid if intentional, documented, and tested.

Watch for candidates who replace the default but cannot explain object sharing.

2. How do assignment, shallow copying, and deep copying differ?

Ask what happens after assigning one nested dictionary to another variable, calling dict.copy(), and modifying an inner list.

Expected evidence:

  • Assignment binds another name to the same object.
  • A shallow copy creates a new outer container but shares references to nested objects.
  • A deep copy recursively copies supported objects, with mechanisms for cycles and customization.
  • Deep copying can be expensive or inappropriate for objects representing external resources.

For a senior follow-up, ask how they would avoid unintended mutation in a configuration pipeline. Good alternatives include immutable representations, explicit reconstruction, and clearer ownership—not automatically applying deepcopy() everywhere.

3. When would you use a generator instead of a list?

Use a realistic example: processing a large log file and emitting matching records.

Strong candidates explain lazy evaluation, incremental consumption, and potentially lower peak memory. They should also recognize that generators are generally single-pass and may defer errors until iteration.

Ask what changes if the caller needs sorting, repeated traversal, or random access. A list may be simpler and appropriate when the input is bounded. Streaming is not automatically faster, and retaining downstream results can eliminate the memory advantage.

4. How should exceptions and resource cleanup be handled?

Ask candidates to review a function that opens a file, parses JSON, catches Exception, and returns an empty dictionary on any failure.

Look for these distinctions:

  • An empty result is not equivalent to unreadable or malformed input.
  • Expected failures should be handled at a meaningful boundary.
  • Exception chaining can preserve the underlying cause.
  • Context managers provide reliable cleanup.
  • Logging and rethrowing at every layer creates duplicate noise.

The official Python tutorial on errors and exceptions provides a useful baseline. Ask candidates to design the caller’s behavior, not simply replace one except clause with another.

5. What do type hints guarantee at runtime?

A good answer states that annotations ordinarily do not enforce types by themselves. Tools such as mypy and Pyright perform static analysis; libraries such as Pydantic can validate data at runtime when explicitly used.

Give candidates an external JSON payload and ask where validation belongs. Strong answers distinguish untrusted boundary data from internal typed objects.

Probe their understanding of Any, optional values, and structural typing with Protocol. Avoid requiring obscure typing syntax unless maintaining a typed library is central to the role.

Concurrency and performance questions

6. How would you choose between threads, processes, and asyncio?

Describe a service that fetches several remote resources and then performs CPU-intensive transformation.

A strong candidate distinguishes the workload phases:

  • Threads: Often useful for blocking I/O and libraries with synchronous interfaces.
  • Asyncio: Useful for many concurrent I/O operations when the stack supports nonblocking execution.
  • Processes: Can provide parallel execution for CPU-bound Python work, with serialization and coordination costs.

Candidates should qualify statements about the global interpreter lock. Conventional GIL-enabled CPython limits simultaneous execution of Python bytecode across threads, but native extensions can release the GIL. Free-threaded CPython builds also exist; availability and dependency compatibility matter.

Do not reward “Python threads never run in parallel.” Ask which interpreter build and libraries the candidate assumes.

7. Why can an async endpoint still block other requests?

Consider a FastAPI async def handler that calls a synchronous HTTP client or performs expensive Python computation.

Expected reasoning: declaring a function async does not make its contents nonblocking. Blocking work on the event-loop thread delays other tasks.

Possible remedies include an async client such as HTTPX’s AsyncClient, appropriately bounded thread offloading for blocking I/O, or moving CPU-heavy work to another execution environment.

Follow up with timeouts, cancellation, and concurrency limits. The official asyncio documentation is the reference point, but the interview should test operational reasoning rather than API memorization.

8. How would you investigate a slow Python service?

A useful answer starts with measurement and hypothesis formation, not rewriting loops.

Ask candidates to:

  1. Define the symptom: latency, throughput, CPU, memory, or queue delay.
  2. Identify representative requests and realistic load.
  3. Separate database, network, serialization, and application time.
  4. Profile the relevant component.
  5. Change one suspected bottleneck and verify the result.

Named tools may include cProfile, tracemalloc, py-spy, database query plans, and OpenTelemetry traces.

Strong candidates discuss N+1 queries, connection-pool exhaustion, and oversized payloads before assuming Python execution speed is the problem. Benchmarks should preserve correctness and reflect production behavior.

Testing, APIs, and production judgment

9. How would you test code that calls an external API?

Look for a layered approach:

  • Unit tests for transformation and decision logic.
  • Controlled HTTP responses for success, timeout, malformed payload, and rate-limit cases.
  • Integration or contract checks for assumptions mocks cannot verify.
  • Deterministic tests without unnecessary network dependence.

With pytest, candidates should understand fixtures, parametrization, and patch scope. The official pytest documentation offers a shared reference for interviewers.

A warning sign is mocking every internal function until the test verifies implementation details rather than behavior. Ask what failure the proposed test would actually catch.

10. How would you prevent duplicate effects when retrying a request?

Use a concrete scenario: a Python worker times out after sending a payment or job-submission request.

Good answers recognize that a timeout does not prove the remote operation failed. Retrying may duplicate the effect.

Look for idempotency keys, persistent operation state, unique constraints, reconciliation, and bounded retries with backoff and jitter. Candidates should identify which failures are retryable and respect a total time budget.

For senior roles, ask where guarantees break across a database and a message broker. Reward precise limits rather than blanket claims of “exactly-once processing.”

11. How would you make a database update safe under concurrency?

Describe two workers trying to reserve the final available item.

Candidates should discuss transactions and an appropriate coordination mechanism: conditional updates, row locks, or optimistic concurrency, depending on the database and workload.

Django ORM or SQLAlchemy familiarity is useful, but the critical evidence is understanding that a read followed by an unchecked write can race.

Follow up on transaction duration, deadlocks, and retries. An in-process Python lock does not coordinate independent service instances.

12. What would you review before deploying a Python change?

Expect concrete checks tied to the change:

  • Tests and static checks pass.
  • Dependencies and supported Python versions are explicit.
  • Secrets and sensitive data are excluded from code and logs.
  • Database migrations have a safe rollout sequence.
  • Metrics and logs can expose failure.
  • Rollback behavior is understood.

Tools may include Ruff, mypy, pip, uv, Poetry, and container-image scanning. Do not require one preferred toolchain; assess whether the candidate understands reproducibility and compatibility.

For security-sensitive work, ask why untrusted pickle data is unsafe and why shell command construction deserves scrutiny.

A practical coding exercise with evaluation criteria

Build a bounded-memory record aggregator

Give candidates newline-delimited JSON records containing customer_id and amount_cents. Ask them to total amounts per customer and handle invalid records according to an explicit policy.

Provide a small fixture containing valid records, missing fields, malformed JSON, and repeated customers. State whether negative amounts are allowed and whether booleans count as valid integers; Python’s bool is a subclass of int, making validation worth discussing.

Evaluate:

  • Correctness: Totals match the specified rules.
  • Error behavior: Invalid records are observable rather than silently lost.
  • Memory awareness: Input is streamed rather than loaded wholesale.
  • Maintainability: Parsing, validation, and aggregation have clear responsibilities.
  • Testing: Edge cases are demonstrated.

The important trade-off: streaming input does not guarantee bounded total memory if unique customer IDs grow without limit. Strong candidates identify the aggregation-state cost and propose a database, partitioning, or external sorting when necessary.

Keep the live task narrow. For take-home work, state an expected timebox and avoid requiring unpaid production-ready infrastructure.

Run the interview in five steps

  1. Create a competency map. Choose the essential skills for the role and identify evidence for each.
  2. Select a consistent question set. Use the same core prompts across candidates, with predefined follow-ups.
  3. Explain the working conditions. State whether documentation, internet search, and AI tools are allowed.
  4. Observe a realistic task. Ask candidates to explain decisions, test assumptions, and respond to one requirement change.
  5. Score independently before discussion. Record concrete evidence before sharing overall impressions.

If AI assistance is allowed, evaluate verification, debugging, and ownership of generated code. If it is prohibited, provide a realistic environment with documentation access rather than turning the exercise into a memory test.

Use an anchored hiring scorecard

Dimension1: Below requirements2: Meets requirements3: Exceeds requirements
Python semanticsMisunderstands shared state or iterationExplains and applies core behaviorAnticipates subtle ownership and API issues
ImplementationMisses central requirementsProduces correct, readable codeHandles change without unnecessary complexity
TestingCovers only the happy pathTests boundaries and failure pathsIdentifies integration and contract risks
Production judgmentIgnores retries or resource limitsHandles expected operational failuresExplains cross-system guarantees and limits
CommunicationAssumptions remain unclearExplains choices and asks useful questionsMakes trade-offs explicit and incorporates feedback

Set expectations before interviewing. Not every dimension deserves equal weight, and “not observed” should remain distinct from a low score.

For senior hires, require evidence of production judgment rather than compensating for its absence with rapid coding. For juniors, distinguish teachable gaps from persistent misunderstandings.

Common Python interviewing mistakes

  • Overusing trivia: Metaclass puzzles rarely predict everyday delivery unless the role involves framework internals.
  • Confusing speed with competence: A slightly slower implementation with meaningful tests can provide stronger evidence.
  • Rejecting unfamiliar tools: Evaluate transferable concepts across Django, Flask, and FastAPI.
  • Ignoring version assumptions: Typing features and concurrency behavior depend on the Python environment.
  • Leaving requirements hidden: Surprise edge cases measure guessing unless ambiguity handling is deliberately being assessed.
  • Scoring by intuition: Record behaviors and examples, not labels such as “not senior enough.”
  • Asking everything: A focused set with substantive follow-ups is more informative than a rushed checklist.

For adjacent hiring guides, browse more Interview questions topics.

Frequently asked questions

What are the most important Python developer interview questions?

Prioritize mutable state, iteration, exception handling, testing, and workload-appropriate concurrency. Add database and API questions for backend roles, or memory and data-validation questions for pipeline roles. Each question should connect to a task the hire will perform.

Should a Python interview include algorithms?

Yes, when algorithmic reasoning matters to the job. Collections, complexity, and practical data processing are broadly useful. Advanced puzzle-solving should not dominate interviews for roles primarily maintaining APIs, automation, or business workflows.

How should senior Python developers be evaluated?

Ask them to reason across boundaries: retries, transactions, cancellation, deployment, observability, and compatibility. Require explicit assumptions and trade-offs. Seniority should appear in problem framing and risk management, not just knowledge of advanced syntax.

Is Django or FastAPI experience mandatory?

Only when immediate framework-specific productivity is essential. Otherwise, test HTTP semantics, validation, persistence, concurrency, and testing practices. Strong fundamentals and demonstrated learning can be more valuable than familiarity with a particular framework’s decorators.

Have a question about this topic?

Ask the community and get answers from practitioners.

Start a discussion