Interview Q&A · Python · 25 questions in this topic
Scenario-Based Interview Questions — Python Interview Q&A
Engineering-judgment questions about production systems — debugging, profiling, caching, configuration, testing and migration decisions, with the trade-offs spelled out. Part of Scenario-Based Interview Questions · 375 questions in the Python bank.
How would you optimize slow Python code in a production application?
Answer
Profile first to find the actual bottleneck (never guess), then apply a targeted fix: better algorithm/data structure choice, caching repeated work, offloading to C-optimized libraries (NumPy), or parallelizing if the workload is genuinely CPU-bound.
A structured approach: (1) reproduce the slowness with a realistic workload, (2) profile with cProfile to find the actual hot path, (3) check if it's algorithmic (wrong Big-O complexity, data structure choice) before reaching for parallelism, (4) only then consider caching (lru_cache), vectorization, or concurrency.
Example
# Step 1: Profile to find the actual bottleneck import cProfile cProfile.run("slow_function()") # Step 2: Common fixes based on what profiling reveals # - O(n^2) algorithm using nested loops -> switch to a set/dict for O(1) lookups # - Repeated expensive computation -> @lru_cache # - String concatenation in a loop -> "".join(parts) instead of += in a loop # - Heavy numerical work -> NumPy vectorization instead of manual Python loops
💡 Lead with "I'd profile first" before naming any specific technique — interviewers specifically watch for candidates who jump straight to "I'd add caching/threads" without establishing where the actual time is going.
How would you process a 10 GB file that doesn't fit comfortably in memory?
Answer
Never load the whole file at once — process it line-by-line (for text) or in fixed-size chunks (for binary/non-lineoriented data) using generators, keeping memory usage constant regardless of file size and.
If the file needs multiple passes or complex aggregation, consider whether a streaming library (pandas with chunksize) or loading the data into a proper database for querying is more appropriate than hand-rolled streaming logic — the right tool depends on what you ultimately need to compute from the data.
Example
def process_large_file(path): total = 0 with open(path, encoding="utf-8") as f: for line in f: # one line in memory at a time if "ERROR" in line: total += 1 return total # For structured data too large for pandas' default in-memory approach: import pandas as pd for chunk in pd.read_csv("huge_file.csv", chunksize=100_000): process(chunk) # process 100k rows at a time instead of all 10 GB at once
💡 Ask a clarifying question if the format isn't specified — "is this a text log file, a CSV, or binary data?" — since the right chunking strategy differs; this shows structured thinking rather than assuming one universal answer.
How would you debug a memory leak in a long-running Python service?
Answer
Use tracemalloc (standard library) to snapshot memory usage at different points in time and compare them, identifying which objects are accumulating; also check for common leak sources — reference cycles involving __del__, growing caches with no eviction policy, and event listeners/callbacks that are registered but never unregistered.
"Memory leak" in Python usually doesn't mean truly unreachable memory (the garbage collector handles that) — it typically means objects are still reachable (and therefore never collected) because something is unexpectedly still holding a reference to them, often a module-level cache, a list that only ever grows, or a subscriber list.
Example
import tracemalloc tracemalloc.start() snapshot1 = tracemalloc.take_snapshot() # ... run the suspected leaking code for a while ... snapshot2 = tracemalloc.take_snapshot() top_stats = snapshot2.compare_to(snapshot1, "lineno") for stat in top_stats[:5]: print(stat) # shows exactly which lines are allocating the most NEW memory
💡 Mention that a "memory leak" in a garbage-collected language almost always means "objects are unexpectedly still reachable," not "memory that's truly lost" — this framing shows you understand what's actually happening, not just how to run a diagnostic tool.
How would you design a reusable, well-structured Python module or package?
Answer
Keep a clear public API (controlled via __init__.py and __all__), separate concerns into focused modules, write docstrings and type hints, include tests, and avoid tight coupling to specific environments (hardcoded paths, global state) so it's genuinely reusable elsewhere.
A key design principle is minimizing what the package exposes publicly — internal helper modules/functions (conventionally prefixed with _) can change freely without breaking users, while the small, deliberate public surface is what you commit to keeping stable.
Example
mypackage/ __init__.py # exposes the deliberate public API core.py # main logic _internal_helpers.py # private, not part of the public API exceptions.py # custom exception hierarchy tests/ test_core.py pyproject.toml # packaging metadata, dependencies README.md # __init__.py from .core import main_function from .exceptions import MyPackageError __all__ = ["main_function", "MyPackageError"]
💡 Emphasize "a small, deliberate public API that I can keep stable, versus internal details I'm free to change" — this signals you think about long-term maintainability, not just getting code to work once.
How would you improve the performance of a slow REST API?
Answer
Profile to find whether the bottleneck is the database (slow queries, missing indexes, N+1 query problems), the application logic (CPU-bound processing), or external calls (slow third-party APIs) — then apply the targeted fix: query optimization, caching, async I/O for concurrent external calls, or pagination for large responses.
The "N+1 query problem" (fetching a list, then making a separate database query for each item's related data) is one of the single most common real-world API performance issues — batching those into one query (or using the ORM's eager-loading features) often produces the single largest improvement.
Example
# N+1 problem: one query for the list, then N more queries in a loop users = get_all_users() # 1 query for user in users: user.orders = get_orders_for_user(user.id) # N additional queries! # Fixed: one batched query instead users = get_all_users() user_ids = [u.id for u in users] all_orders = get_orders_for_users(user_ids) # 1 query for everyone orders_by_user = group_by_user_id(all_orders) # then just an in-memory lookup
💡 Naming the N+1 query problem by name, and describing the batching fix specifically, is one of the highest-signal answers you can give for API performance questions — it comes up constantly in real systems.
When would you choose a generator over a list in a real application?
Answer
Choose a generator when you're processing a large or unbounded dataset that you only need to iterate over once, especially in a pipeline where each stage can process one item at a time — a list is better when you need random access, multiple passes, or the data is genuinely small.
The practical decision often comes down to: "will I iterate over this more than once, or need to index into it?" If yes, use a list. If you're building a one-directional processing pipeline over potentially huge data (log processing, streaming API responses, ETL), a generator (or chain of generators) is almost always the better choice.
Example
# Good generator use case: streaming ETL pipeline over a huge dataset def read_records(path): with open(path) as f: for line in f: yield parse_record(line) def filter_valid(records): for r in records: if r.is_valid(): yield r # Processes the entire file with roughly constant memory, one record at a time for record in filter_valid(read_records("huge_dataset.csv")): save_to_database(record)
💡 If the interviewer pushes on "but what if I need to loop over it twice," that's exactly the signal a generator is the wrong choice — being able to recognize and state that boundary clearly is the real point of this question.
When would you reach for multiprocessing over threading or asyncio in a real project?
Answer
When the workload is genuinely CPU-bound — heavy numerical computation, image/video processing, complex data transformations — and you need to use multiple CPU cores simultaneously to actually speed things up, since the GIL prevents threading from achieving that.
Before reaching for multiprocessing, it's worth checking whether the CPU-bound work could instead be delegated to an already-optimized C library (NumPy, pandas) that releases the GIL internally — sometimes vectorizing the computation solves the performance problem without needing to manage separate processes at all.
Example
# Scenario: resizing thousands of images -- genuinely CPU-bound work from concurrent.futures import ProcessPoolExecutor def resize_image(path): # ... CPU-intensive image processing ... return f"resized {path}" image_paths = [f"image_{i}.jpg" for i in range(1000)] with ProcessPoolExecutor() as executor: results = list(executor.map(resize_image, image_paths)) # Genuinely parallelized across CPU cores -- threading wouldn't help here
💡 A senior answer checks "could a vectorized library solve this without multiprocessing at all?" before committing to the added complexity of managing separate processes — showing you don't reach for the heaviest tool by default.
How would you efficiently process millions of database records?
Answer
Never load millions of rows into memory at once — use server-side cursors or paginated/batched queries to fetch and process records in manageable chunks, and use bulk insert/update operations rather than one-row-at-a-time database calls, which are dramatically slower due to per-query overhead.
The most common real-world mistake here is looping over records and issuing an individual database write for each one — batching writes (inserting hundreds or thousands of rows per query) can be an order of magnitude faster due to reduced network round-trips and transaction overhead.
Example
# Slow: one query per record for record in millions_of_records: db.execute("INSERT INTO table VALUES (?)", record) # huge overhead, one round- trip each # Much faster: batched inserts batch = [] for record in millions_of_records: batch.append(record) if len(batch) >= 1000: db.execute_many("INSERT INTO table VALUES (?)", batch) # one round-trip per 1000 rows batch.clear() if batch: db.execute_many("INSERT INTO table VALUES (?)", batch) # flush the remainder
💡 Quantifying the batching improvement ("one query per row vs. one query per thousand rows can be a 100x+ difference in wall-clock time") makes this answer far more convincing than a general statement about "using batches."
How would you structure a production-grade Python project?
Answer
Separate application code, tests, configuration, and documentation into clear top-level directories; use a proper package layout (a src/ directory is a common, robust convention); manage dependencies with a lock file; and keep configuration (especially secrets) out of source code entirely, loaded from environment variables instead.
The "src layout" (putting your actual package inside a src/ directory rather than at the project root) is increasingly recommended because it prevents accidentally importing your package from the working directory instead of the properly installed version — a subtle bug that a flat layout can hide.
Example
myproject/ src/ myproject/ __init__.py core.py api/ models/ tests/ test_core.py pyproject.toml .env.example # documents required environment variables, without real secrets README.md .gitignore
💡 Mentioning the "src layout" specifically, and why it helps (avoiding accidental local-directory imports masking real packaging bugs), is a detail that distinguishes real production experience from a purely academic answer.
How would you resolve a dependency conflict between two packages your project needs?
Answer
First, understand exactly what's conflicting (which shared dependency, and which version ranges each package requires) using pip's error output or pip index versions; then try upgrading the more flexible package, look for a compatible version range that satisfies both, or as a last resort, isolate the conflicting tools into separate environments, Q180).
Before assuming a conflict is truly unresolvable, check whether one of the packages has a newer release that relaxed its version constraint — dependency conflicts are sometimes just a matter of an outdated pinned version rather than a fundamental incompatibility.
Example
# Diagnose the conflict pip install package-a package-b # ERROR: package-a requires urllib3<2.0, but package-b requires urllib3>=2.0 # Check for newer versions that might relax the constraint pip index versions package-a # If truly incompatible, isolate them into separate environments/services python -m venv env_for_package_a python -m venv env_for_package_b
💡 Walking through this as a diagnostic process (read the exact conflict, check for updates, then consider isolation) reads as much stronger than jumping straight to "I'd just use a different virtual environment."
How would you design a rate limiter for an API in Python?
Answer
A common approach is the "token bucket" or "sliding window" algorithm: track how many requests a client has made in a recent time window, and reject (or delay) requests once they exceed a defined threshold — implemented with an in-memory counter for a single-server setup, or a shared store like Redis for a distributed system.
The key design decision is where state lives: an in-process counter (using a dict or a library like cachetools) works for a single server instance, but a distributed system with multiple servers needs a shared, centralized store (Redis is the standard choice) so rate limits are enforced consistently across all instances.
Example
import time from collections import defaultdict class SimpleRateLimiter: def __init__(self, max_requests, window_seconds): self.max_requests = max_requests self.window_seconds = window_seconds self.requests = defaultdict(list) def allow_request(self, client_id): now = time.time() window_start = now - self.window_seconds # Drop timestamps outside the current window self.requests[client_id] = [t for t in self.requests[client_id] if t > window_start] if len(self.requests[client_id]) < self.max_requests: self.requests[client_id].append(now) return True return False limiter = SimpleRateLimiter(max_requests=5, window_seconds=60) print(limiter.allow_request("user_123")) # True, until the limit is hit
💡 Immediately raise the single-server vs. distributed-system distinction — it shows you're thinking about how this design would actually need to change in a real, horizontally-scaled production environment, not just a single-process toy example.
How would you implement caching in a Python web application?
Answer
For simple, single-process cases, functools.lru_cache works for pure function results. For a real web application, an external cache like Redis or Memcached is standard, since it's shared across multiple application server processes and survives individual process restarts.
The hardest part of caching is invalidation — deciding when cached data becomes stale and needs to be refreshed. Common strategies include a time-based expiration (TTL), explicitly invalidating the cache when the underlying data changes, or a combination of both for defense in depth.
Example
import redis import json cache = redis.Redis(host="localhost", port=6379) def get_user(user_id): cache_key = f"user:{user_id}" cached = cache.get(cache_key) if cached: return json.loads(cached) # cache hit user = fetch_user_from_database(user_id) # cache miss -- slow path cache.setex(cache_key, 300, json.dumps(user)) # cache for 5 minutes (TTL) return user def update_user(user_id, data): update_user_in_database(user_id, data) cache.delete(f"user:{user_id}") # invalidate on write, so stale data isn't served
💡 "There are only two hard problems in computer science: cache invalidation and naming things" is a well-known joke worth referencing lightly — but back it up immediately with your actual invalidation strategy (TTL + explicit invalidation on writes) rather than just the punchline.
How would you handle configuration management across dev/staging/ production environments?
Answer
Load configuration from environment variables (or a.env file locally, loaded via a library like pythondotenv), never hardcode environment-specific values or secrets directly in source code, and keep a documented example (.env.example) showing what variables are required without exposing real values.
This follows the widely referenced "twelve-factor app" methodology's config principle: strict separation of config from code, so the exact same codebase can run correctly in any environment purely by changing its environment variables, with zero code changes required between dev, staging, and production.
Example
import os from dotenv import load_dotenv load_dotenv() # loads variables from a local .env file during development DATABASE_URL = os.environ["DATABASE_URL"] # required -- fails loudly if missing DEBUG = os.environ.get("DEBUG", "false").lower() == "true" MAX_CONNECTIONS = int(os.environ.get("MAX_CONNECTIONS", "10")) # .env.example (committed to the repo, no real secrets): # DATABASE_URL=postgresql://user:password@localhost/dbname # DEBUG=true # MAX_CONNECTIONS=10
💡 Mentioning "the twelve-factor app" methodology by name for the config principle signals familiarity with widely adopted, industry-standard practices rather than an ad-hoc personal approach.
How would you design a retry mechanism for unreliable network calls?
Answer
Retry a limited number of times, only for specific transient failure types (network timeouts, 5xx server errors — not 4xx client errors, which won't succeed on retry), using exponential backoff (increasing delay between attempts) to avoid overwhelming an already-struggling service — this directly builds on the retry decorator from, Q164.
Adding "jitter" (a small random variation to the backoff delay) is an important refinement in real distributed systems — without it, many clients that failed at the same moment would all retry at exactly the same intervals, creating synchronized bursts of load ("thundering herd") on the recovering service.
Example
import time import random def call_with_retry(func, max_attempts=5, base_delay=1): for attempt in range(1, max_attempts + 1): try: return func() except (ConnectionError, TimeoutError) as e: if attempt == max_attempts: raise delay = base_delay * (2 ** (attempt - 1)) + random.uniform(0, 1) # backoff + jitter print(f"Attempt {attempt} failed, retrying in {delay:.1f}s") time.sleep(delay)
💡 Mentioning "jitter" specifically, and explaining the thundering herd problem it prevents, is a detail that distinguishes candidates with real distributed-systems experience from those who've only seen a basic retry loop.
How would you write unit tests for a function that depends on the current time or randomness?
Answer
Make the dependency injectable rather than hardcoded — pass the current time or a random generator as a parameter (with a sensible default for normal use) — or use mocking (unittest.mock.patch) to control what datetime.now() or random.random() return during the test, making the test deterministic and repeatable.
This is a direct application of writing testable code from the start (Q316): a function hardcoding a call to datetime.now() deep inside its logic is inherently hard to test reliably, since the "correct" expected output changes every time the test runs — designing for injectability up front avoids this entirely.
Example
from datetime import datetime from unittest.mock import patch # Harder to test: time is hardcoded inside the function def is_expired_hard(expiry_date): return datetime.now() > expiry_date # Easier to test: time is injectable, with a sensible default def is_expired_easy(expiry_date, current_time=None): current_time = current_time or datetime.now() return current_time > expiry_date # Testing the "easy" version needs no mocking at all -- just pass a fixed time in: def test_is_expired_easy(): assert is_expired_easy(datetime(2024, 1, 1), current_time=datetime(2025, 1, 1)) is True
💡 Show both approaches, but clearly state a preference for dependency injection over mocking when you have the choice — it results in simpler, more robust tests that don't need to reach into another module's internals.
How would you design a Python application to be testable from the start?
Answer
Favor pure functions where possible, Q78), inject dependencies (database connections, API clients, current time) rather than hardcoding them inside functions/classes, keep I/O and business logic separated, and design around small, focused units that can be tested independently.
A useful mental model: the parts of your application that make decisions (business logic) should be separable from the parts that talk to the outside world (databases, APIs, the filesystem) — this separation lets you test the decisionmaking logic thoroughly with plain, fast unit tests, while integration tests cover the smaller surface area that actually touches external systems.
Example
# Harder to test: business logic tangled directly with I/O def process_order_tangled(order_id): order = database.get_order(order_id) # I/O if order.total > 100: order.discount = order.total * 0.1 # business logic database.save_order(order) # I/O # Easier to test: business logic separated and pure def calculate_discount(order_total): # pure function -- trivial to test return order_total * 0.1 if order_total > 100 else 0 def process_order_clean(order_id): # thin I/O layer, calls the pure logic order = database.get_order(order_id) order.discount = calculate_discount(order.total) database.save_order(order) def test_calculate_discount(): assert calculate_discount(150) == 15.0 # no database, no mocking needed at all
💡 "Separate what decides from what does" is a compact, memorable way to summarize this design principle — using it explicitly in your answer signals a clear mental model, not just a list of unrelated tips.
How would you handle sensitive data like API keys and passwords in a Python application?
Answer
Never hardcode secrets in source code or commit them to version control — load them from environment variables or a dedicated secrets manager (AWS Secrets Manager, HashiCorp Vault, etc.), and ensure.env files containing real secrets are explicitly excluded via.gitignore.
Beyond just avoiding accidental commits, a mature approach also considers secret rotation (changing credentials periodically without downtime) and least-privilege access (each service only has access to the specific secrets it actually needs, not a shared set of "everything" credentials).
Example
import os # Never do this: # API_KEY = "sk-live-abc123..." # hardcoded secret, visible in source control forever # Do this instead: API_KEY = os.environ["API_KEY"] # loaded from environment, never committed to source # .gitignore # .env # *.pem # secrets/
How would you debug a Python application that intermittently crashes in production?
Answer
Ensure comprehensive logging is already in place (especially logger.exception() for full tracebacks, Q130) so the next occurrence provides real diagnostic data, look for patterns in when the crash occurs (specific input, load conditions, time of day), and consider whether it's a race condition if concurrency is involved.
"Intermittent" is the key word here — it usually points to either a race condition (timing-dependent), a resource exhaustion issue (memory, file descriptors, connection pool) that only manifests under load, or an edge case in specific input data that only occasionally appears — a structured investigation checks each of these categories rather than guessing randomly.
Example
import logging logger = logging.getLogger(__name__) def process_request(request): try: return handle(request) except Exception: # Log enough context to reproduce and diagnose the NEXT occurrence logger.exception("Failed processing request: %s", getattr(request, "id", None)) raise # Also worth checking systematically: # - Does it correlate with high load / high concurrency? (race condition, resource exhaustion) # - Does it correlate with specific input data? (edge case, unhandled data shape) # - Does it correlate with time (e.g., always after N hours)? (memory leak, connection pool exhaustion)
💡 Frame your answer as a systematic investigation process (check logs, check for patterns in timing/ load/input, form a hypothesis, test it) rather than a single "here's the fix" — intermittent bugs specifically require methodical elimination, and interviewers want to see that discipline.
How would you design a data pipeline that processes data from multiple sources?
Answer
Normalize each source into a common internal representation as early as possible, isolate source-specific parsing logic so new sources can be added without touching the rest of the pipeline, and design each stage to be independently testable — a chain of generator-based stages is a natural fit for this.
A robust pipeline design also needs to consider failure isolation: one malformed record from one source shouldn't halt processing of everything else, so validation and error handling at the ingestion boundary (as data enters the pipeline) is critical, rather than letting bad data propagate deep into downstream logic.
Example
def normalize_source_a(raw_record): return {"id": raw_record["user_id"], "value": raw_record["amount"]} def normalize_source_b(raw_record): return {"id": raw_record["uid"], "value": raw_record["total"]} def ingest(source_a_records, source_b_records): for record in source_a_records: try: yield normalize_source_a(record) except (KeyError, TypeError): log_bad_record("source_a", record) # isolate failures, don't halt the pipeline for record in source_b_records: try: yield normalize_source_b(record) except (KeyError, TypeError): log_bad_record("source_b", record) def process_pipeline(source_a_records, source_b_records): for normalized in ingest(source_a_records, source_b_records): yield transform(normalized) # everything downstream works with ONE common shape
💡 Explicitly mentioning failure isolation ("one bad record from one source shouldn't crash the entire pipeline") demonstrates production-mindedness beyond just getting the happy path working.
How would you decide between a monolithic Python application and microservices?
Answer
Start with a well-structured monolith unless you have a specific, concrete reason for microservices (independent scaling needs for different components, genuinely separate teams needing independent deployment cycles, or fundamentally different technology requirements per component) — microservices introduce real operational complexity (network calls, distributed debugging, deployment orchestration) that isn't justified for most applications, especially early on.
A common, pragmatic path is starting with a "modular monolith" — a single deployable application with clean internal module boundaries (Q304's package structure principles applied internally) — which can later be split into actual microservices along those same boundaries if and when a concrete need arises, rather than guessing at service boundaries prematurely.
Example
# A "modular monolith" -- one deployable unit, but clean internal boundaries: myapp/ users/ # could become its own service later, if truly needed models.py service.py orders/ # same -- separated internally, but one deployment for now models.py service.py shared/ database.py
💡 "Start with a modular monolith, split into services only when a concrete, measured need arises" is a well-regarded, pragmatic industry position — it shows judgment against jumping to microservices as a default trend rather than a deliberate architectural decision.
How would you handle backward compatibility when changing a public API or library?
Answer
Follow semantic versioning (breaking changes only in major version bumps), deprecate old functionality with clear warnings before removing it (using Python's warnings.warn(., DeprecationWarning)), and give consumers a documented migration path and a reasonable transition period before the old behavior is actually removed.
A deprecation period lets existing users update their code on their own schedule rather than being broken by surprise on an upgrade — the deprecation warning itself should clearly state what to use instead, not just that the old approach is going away.
Example
import warnings def old_function(x): warnings.warn( "old_function() is deprecated and will be removed in v3.0; " "use new_function() instead.", DeprecationWarning, stacklevel=2, ) return new_function(x) def new_function(x): return x * 2
💡 Mentioning semantic versioning (MAJOR.MINOR.PATCH, where breaking changes only happen in MAJOR bumps) explicitly ties this to an industry-standard convention that most engineers and their tooling already expect and rely on.
How would you approach reviewing a Python pull request?
Answer
Check correctness first (does it actually solve the stated problem, are edge cases handled), then readability and maintainability (clear naming, appropriate structure), then adherence to project conventions (style, patterns already established), and finally test coverage — roughly in that priority order, since a perfectly styled but incorrect change is still wrong.
A good reviewer distinguishes between blocking issues (bugs, security concerns, breaking changes) and nonblocking suggestions (stylistic preferences, minor readability nitpicks) — conflating the two can either let real problems through or unnecessarily stall a good change over trivial disagreements.
Example
# A review comment distinguishing severity levels clearly: # BLOCKING: this will raise a KeyError if 'email' is missing from the payload # user_email = payload["email"] # SUGGESTION (non-blocking): consider extracting this into a named helper # for readability, but not required for this PR # if user.is_active and user.subscription.tier == "premium" and not user.is_banned:
💡 Explicitly distinguishing "blocking" from "non-blocking, just a suggestion" feedback in your review comments is a concrete practice that shows real collaborative experience, not just technical review skill.
How would you monitor a Python application in production?
Answer
Combine structured logging, Q130), metrics (request rates, error rates, latency percentiles — often exported to a system like Prometheus), and error tracking (a service like Sentry that aggregates and alerts on exceptions) — together these answer "is it working," "how well is it performing," and "what exactly broke," respectively.
Logs alone are insufficient at scale — they're great for deep investigation of a specific incident, but metrics (aggregated, queryable over time) are what let you notice a problem exists in the first place (a spike in error rate, a latency regression) before a customer reports it.
Example
import logging import time logger = logging.getLogger(__name__) def handle_request(request): start = time.perf_counter() try: result = process(request) duration = time.perf_counter() - start metrics.histogram("request_duration_seconds", duration) # illustrative metrics call metrics.increment("requests_total", tags={"status": "success"}) return result except Exception: metrics.increment("requests_total", tags={"status": "error"}) logger.exception("Request failed: %s", getattr(request, "id", None)) # full traceback, for later raise
💡 Structuring your answer around the three pillars — logs (what happened, in detail), metrics (aggregate trends over time), and error tracking (aggregated, actionable exceptions) — gives a complete, organized answer instead of a single-tool response.
How would you approach migrating a codebase between major dependency versions (e.g., a major framework upgrade)?
Answer
Read the migration guide and changelog thoroughly first, ensure strong test coverage exists before starting (so you can trust that passing tests mean the migration didn't break anything), upgrade incrementally where possible rather than jumping multiple major versions at once, and use automated tools (like 2to3 was for Python 2→3) where available.
If test coverage is weak going into a major migration, it's often worth investing in tests for the most critical paths first — otherwise you're migrating blind, unable to distinguish "this broke because of the migration" from "this was already subtly broken and nobody noticed."
Example
# Migration approach, roughly in order: 1. Read the official migration guide / changelog for breaking changes 2. Ensure critical-path test coverage exists BEFORE starting 3. Create a dedicated branch; upgrade the dependency in isolation 4. Run the full test suite; fix failures one at a time, understanding each root cause 5. Manually test key user-facing flows the test suite might not cover 6. Deploy to a staging environment before production 7. Roll out gradually if possible (feature flag, canary deployment) rather than all at once
💡 "I'd make sure test coverage was solid before starting the migration" is a subtle but important point — it shows you understand that migrations are only as safe as the tests validating them, not just a mechanical version bump.
How would you onboard a new developer to a large, unfamiliar Python codebase?
Answer
Provide a working local development setup that's quick and reliable (ideally a single documented command or script), point them to the highest-value entry points (main modules, key architectural docs, the test suite as executable documentation), and pair them with a small, well-scoped first task that touches representative parts of the codebase without requiring full context upfront.
A frequently underrated onboarding tool is a well-maintained test suite itself — reading tests for a module is often the fastest way to understand its intended behavior and edge cases, frequently more reliable than out-of-date prose documentation elsewhere in the repository.
Example
# A practical onboarding checklist: 1. Can they get the project running locally within the first hour? (README quality matters enormously) 2. Do they know where to find: the test suite, key architectural decisions, the deployment process? 3. Is their first task scoped small enough to complete in a day or two, but real enough to touch actual code review and CI/CD processes? 4. Do they know who to ask, and where prior architectural decisions are documented (if at all)?
💡 If asked this in an interview, it's often really probing whether you write onboarding-friendly code and documentation as you work day-to-day — mentioning that you keep READMEs current and write tests as living documentation ties this "soft skill" question back to concrete engineering habits.
Recommended resourcesAffiliate links · may earn us a commission