Python Interview Questions for Experienced Developers

Experienced Python interviews test the judgement behind a change: caller compatibility, failure handling, performance evidence, dependency management and operational trade-offs. Prepare answers using a concrete service boundary and explain how you would prove the important behaviour. This guide works through a quote calculation with a supplied catalogue lookup, including a checked timeout-translation test.

Aug 27, 2024 - 16:58
Updated: 
103.9k

Python for AI & Automation in AI & Data · Interview preparation

Python Interview Questions for Experienced Developers

Quick answer: Experienced Python interviews test the judgement behind a change: caller compatibility, failure handling, performance evidence, dependency management and operational trade-offs. Prepare answers using a concrete service boundary and explain how you would prove the important behaviour. This guide works through a quote calculation with a supplied catalogue lookup, including a checked timeout-translation test. It also covers profiling, concurrency and cache assumptions. The unit-level evidence is kept separate from claims about real APIs, deployment or application performance.

Key takeaways

  • Identify existing caller contracts before changing an API.
  • Profile representative work before claiming an optimization.
  • Translate expected failures while preserving their causes.
  • Use doubles to test a narrow dependency boundary.
  • Explain cache freshness, ownership and side effects.

Table of Contents

How do you evaluate a change to an existing Python service?

Start with the behaviour callers already depend on. Ask which inputs are accepted, what failures mean, and whether a change alters ordering, mutation, exceptions or result types. An experienced developer should explain a migration path as well as the desired final design.

Proposed changeCompatibility questionEvidence to collect
Return a generator instead of a listDo callers iterate twice or use indexing?Representative caller tests
Raise a domain exceptionWhich callers catch the old exception?Failure-path contract tests
Cache lookup resultsHow long can stale data remain valid?Invalidation policy and freshness tests
Make a parameter keyword-onlyDo existing callers pass it positionally?Call-site inventory and migration plan

In the worked quote example, a supplied product lookup either returns an integer price or times out. The proposed boundary translates that known failure into a domain-specific exception while preserving its cause.

How would you investigate a slow Python application?

Define a representative workload and the symptom first: latency, throughput, memory growth or excessive external calls. The profiling guide explains cProfile’s execution statistics and warns that profiling is not benchmarking. Locate expensive paths, make a focused change and compare under a consistent workload.

If a quote endpoint performs the same catalogue lookup repeatedly, distinguish expensive remote work from Python loop overhead. Batching or reducing duplicate work may help more than rewriting arithmetic. A microbenchmark of a multiplication cannot establish endpoint latency. If someone proposes a cache, ask how price updates reach it, which keys include currency or catalogue version, and whether retaining results creates a memory problem. These questions belong before a speed claim.

How should a public API translate and preserve exceptions?

Catch a failure only where there is a useful recovery or translation policy. A missing optional field, a programmer error and a temporary lookup timeout should not all become the same success-shaped result. The exception tutorial describes exception chaining with raise from, which preserves an underlying cause while presenting a domain-level exception.

In quote_total, TimeoutError becomes PriceUnavailable. Other exceptions propagate, helping expose an unexpected lookup bug. Returning zero after any exception could create a free order, so it would need an explicit business rule and separate review. A follow-up asks whether the operation is safe to retry. The answer depends on side effects, idempotency and a bounded policy, not merely the exception class.

How do you test a dependency boundary without calling a service?

Pass the lookup dependency explicitly and supply a fake or mock in a unit test. The unittest.mock reference documents return values, side effects and call assertions. This fixture verifies one successful total, one translated timeout and the absence of an automatic extra lookup. It uses integer minor units to keep this arithmetic exercise exact; a real pricing contract still needs currency and rounding rules.

The complete code ran in CPython 3.14.4, with no network or database. These checks establish boundary behaviour against the supplied doubles; they do not verify a vendor API or the full checkout workflow.

from unittest.mock import Mock

class PriceUnavailable(Exception):
    pass

def quote_total(product, quantity, lookup):
    try:
        unit_price = lookup(product)
    except TimeoutError as exc:
        raise PriceUnavailable(product) from exc
    return unit_price * quantity

lookup = Mock(return_value=125)
print("total minor units:", quote_total("P7", 3, lookup))
lookup.assert_called_once_with("P7")

unavailable = Mock(side_effect=TimeoutError("fixture"))
try:
    quote_total("P7", 3, unavailable)
except PriceUnavailable as exc:
    print("cause:", type(exc.__cause__).__name__)
print("failure calls:", unavailable.call_count)

Expected output:

total minor units: 375
cause: TimeoutError
failure calls: 1

How do you keep dependency and interpreter changes reviewable?

Record the interpreter version, direct dependencies and how the environment is recreated. The venv reference describes environments that isolate installed packages from the base environment by default. An environment directory is not a portable deployment artifact or a security sandbox.

When upgrading a dependency, review relevant release notes and run tests that cover the APIs the application uses. A frozen package listing captures an installed state, but the deployment plan also needs platform details, supported Python versions and artifact provenance. For this exercise, the only dependency is the standard library, and the receipt records the actual interpreter.

How do you choose concurrency and caching mechanisms?

Explain the work that can overlap and the state that must remain consistent. Async can suit many waiting operations if the libraries cooperate. Processes can isolate CPU work but bring serialization, startup and memory costs. In GIL-enabled CPython, threads have different CPU constraints from free-threaded builds; the free-threading guide describes the distinction and extension compatibility.

For a cache, the functools reference documents argument and result retention. Thread-safe cache bookkeeping does not imply the wrapped function executes once per key. Two concurrent misses may compute twice. If lookup performs billing or another side effect, caching is not an exactly-once safeguard. State who owns cached mutable results and how staleness is handled.

What should an experienced developer explain about design and debugging?

Use a concrete project change and distinguish your contribution from team work. Describe the old failure, the option you selected, the trade-off you accepted and the evidence after the change. If you have only a practice project, label it honestly and show its boundaries.

Interview questionUseful answer directionWeak shortcut
Why use dependency injection?It makes the quote lookup boundary explicit and replaceableEvery dependency needs a framework
How would you debug this failure?Reproduce it, inspect the chained cause and identify the relevant inputCatch all errors and continue
Should this use a singleton?Explain lifetime and ownership before choosing shared stateA singleton always saves resources
What should be logged?Enough context to investigate without sensitive payloadsDump every object and response

A mock can encode an incorrect assumption, so keep contract tests and integration evidence separate. Review whether tests would fail if the implementation called the dependency twice, swallowed a timeout or changed the result unit. Those are meaningful regressions in this small case.

Related reading: Advanced Python mechanisms; Python technical questions; Python object design questions.

References

Frequently Asked Questions

Experienced answers connect implementation choices to caller contracts, failure modes, migration costs and evidence from a specific change.

First identify a representative workload and bottleneck, because optimizing a small expression may not improve the observed application problem.

Exception chaining keeps the underlying failure available for diagnosis while exposing a domain-specific exception to the caller.

A mock checks behaviour against supplied assumptions, while actual compatibility needs separate contract or integration evidence in an appropriate environment.

A virtual environment isolates installed packages by default, but it does not provide a complete security boundary or portable deployment.

A timeout can leave the remote outcome uncertain, so retry decisions require side-effect knowledge, idempotency and a bounded policy.

Concurrent cache misses can execute the wrapped function more than once, even though the cache bookkeeping remains coherent.

Call it a practice project, describe the implemented behaviour and tests, and avoid claiming production traffic or business outcomes.

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Wow Wow 0
Sad Sad 0
Angry Angry 0
Anjali

I am passionate about technology, invention and big challenging tasks on my to- do list. In terms of the work I am doing also at Bunnyshell, I am most passionate about the technologies that we are using., I'm devoted to delivering content that not only informs but also inspires. Whether you need in- depth analysis pieces, educational attendants, or study- provoking opinion pieces, I draft content that resonates with tech suckers and professionals likewise.