Python
217 bites tagged Python — interview questions with model answers, and 60-second explainers.
Explain FastAPI dependency overrides with an in-memory SQLite test example
This tests FastAPI's hook for swapping dependencies cleanly in tests. A strong answer names app.dependency_overrides, defines a test-only in-memory SQLite session, and handles teardown. A red flag is patching globals or mocking ORM instead of dependency.
How do you test a FastAPI GET endpoint with pytest and TestClient?
Import TestClient and app, write a test_ function, call client.get("/items/1"), assert status_code == 200 and json() matches expected data. FastAPI testing with TestClient. Using requests or forgetting test_ prefix.
Which FastAPI CORSMiddleware parameters beyond allow_origins fix a PUT preflight?
Configure allow_methods for PUT and allow_headers for Authorization so the browser approves the cross-origin call. CORS preflight mechanics for non-simple requests.
Write a FastAPI middleware that adds X-Process-Time header
Tests FastAPI lifecycle and header mutation. Strong answers use the http middleware decorator, await call_next, compute elapsed time, and inject X-Process-Time before returning. Red flag: forgetting to await call_next or mutating headers after the return.
Purpose of await next(request) in FastAPI middleware and timing effects
Tests ASGI middleware lifecycle. await next(request) forwards the request downstream to the endpoint and returns the response. Pre-call code touches the request; post-call code touches the response.
How do you send an email without blocking a FastAPI request?
Tests knowledge of FastAPI's BackgroundTasks for post-response work. Strong answer: import it, inject into the endpoint, define a task function, and call add_task before returning. Recommending raw asyncio.create_task or insisting Celery is required.
Implement OAuth2 Password Flow in FastAPI
Tests FastAPI security integration and stateless auth patterns. A strong answer covers the POST /token endpoint returning a JWT, the OAuth2PasswordBearer dependency, and get_current_user decoding the JWT sub.
How should you store user passwords in a database?
Tests knowledge of slow salted hashing versus encryption. Strong answers pick Argon2id or bcrypt, require unique per-user salts, describe verification via re-hashing with constant-time comparison, and cite bcrypt or argon2-cffi.
What are the three components of a JWT?
Tests if you know JWT structure beyond library usage. A strong answer lists header, payload, and signature; notes Base64Url encoding; and gives a registered claim like exp. A red flag is confusing signing with encryption.
How do you protect a FastAPI endpoint using Depends and OAuth2PasswordBearer?
OAuth2PasswordBearer sets the token URL, Depends injects it into the endpoint, and FastAPI validates the Bearer header. your grasp of FastAPI dependency injection for security.
Implement a PATCH endpoint for partial SQLAlchemy updates
Tests PATCH vs PUT and selective ORM updates. Strong answer: all-optional update schema, load existing record, iterate exclude_unset=True fields with setattr, commit. Red flag: updating without excluding unset, which overwrites missing fields with None.
Why synchronous DB libraries block async FastAPI endpoints and correct SQLAlchemy usage
This tests event loop blocking: sync DB calls in async def halt all requests. Answer: sync drivers block the loop despite releasing the GIL; use asyncpg with SQLAlchemy create_async_engine and AsyncSession. Red flag: recommending run_in_executor as default.
How do you use FastAPI dependency injection for database sessions?
Build a generator dependency that yields a session and closes it after; inject via Depends(get_db). FastAPI Depends() for session lifecycle and testability.
Explain SQLAlchemy ORM vs Pydantic models in FastAPI
This tests separation of database schema from API contracts. A strong answer distinguishes SQLAlchemy table rows from Pydantic validation and OpenAPI generation, and notes that create schemas exclude auto-generated IDs.
Describe SQLAlchemy setup in FastAPI from database config to endpoint
Tests FastAPI dependency injection and SQLAlchemy session lifecycle. Good answers cover: engine with pooling, declarative models, a yield-based session dependency, and endpoint queries. Red flag: engine per request or global session shared everywhere.
Why are contextvars better than threading.local in async Python?
This tests whether you know async tasks share OS threads, making thread-local storage unsafe for request state. A great answer notes ContextVar is task-local and resets automatically, while threading.local bleeds across concurrent coroutines.
How do you gracefully cancel and clean up an asyncio task?
This tests asyncio cooperative cancellation and cleanup. A strong answer covers catching CancelledError at await points, using try/finally or async context managers for cleanup, and re-raising.
Unhandled exception in asyncio.create_task(): consequence and detection
Tests Task exception capture vs propagation. Good answer: exceptions are stored in the Task object, the loop keeps running, and the creator must await the task or call task.exception() to retrieve it; unretrieved ones may be logged.
When should you use asyncio.Lock over threading.Lock?
This tests cooperative multitasking knowledge: asyncio.Lock yields to the event loop via await, while threading.Lock blocks the OS thread and freezes the loop. A red flag is claiming threading.Lock works because locks are universal.
Explain the asyncio event loop and cooperative multitasking
Tests if you view the event loop as a single-threaded orchestrator, not magic parallelism. Strong answers note it runs tasks and callbacks, manages a ready queue, and yields control at await. Red flag: calling it multithreading or parallel execution.
How do you safely execute blocking code from an async function
Tests whether you know how to prevent event loop blocking by offloading sync work. Name asyncio.to_thread or run_in_executor, explain ThreadPoolExecutor scheduling, and note when processes beat threads.
Explain await's purpose, awaitable types, and event loop signaling
This tests whether you understand await as a yield point. A strong answer lists three awaitables (coroutines, Tasks, Futures), explains await yields control to the event loop until completion, and warns that a bare coroutine call does not run it.
What is the difference between async def and regular functions?
This tests async def call semantics. A strong answer contrasts regular functions, which execute immediately, with async def, which returns a coroutine object that does nothing until awaited or wrapped in create_task.
Override a FastAPI dependency at the APIRouter level
Tests FastAPI DI scoping limits. Answer: APIRouter has no dependency_overrides; create a sub-app, apply overrides, mount it. Red flag: Claiming router-level overrides exist or mutating global app state.
Get Python bites daily.
Five a day, five minutes, offline. With quizzes so it sticks.
Open testing — you’ll join as an early tester.