Python
217 bites tagged Python — interview questions with model answers, and 60-second explainers.
Pandas loc versus iloc indexing
Loc selects by label and is inclusive of both endpoints; iloc selects by integer position and is exclusive of the stop; passing a string label to iloc fails. practical pandas selection fluency.
Python Virtual Environments
A virtual environment is an isolated Python installation with its own packages, so each project gets the exact dependency versions it needs without conflicting with other projects or the system Python.
Explain multi-stage Docker builds for Python and builder vs runtime
Tests separation of build-time and runtime concerns. A strong answer contrasts the builder stage (gcc, headers, wheels) with the runtime stage (slim base, copied artifacts, no compiler). Red flag: citing size alone while ignoring security and caching.
What are the key responsibilities for Nginx versus Uvicorn?
This tests the reverse-proxy versus ASGI-server boundary. A strong answer gives Nginx TLS termination, static files, buffering, and load balancing, while Uvicorn runs the Python app and async workers.
Walk me through a basic Dockerfile for a FastAPI app
Slim base, install deps before app code to cache layers, expose port, exec-form CMD for Uvicorn. Docker layering and build cache for Python containers. Shell-form CMD or code-before-requirements, killing cache.
How do you inspect WebSocket close codes in FastAPI?
Tests WebSocket lifecycle handling in FastAPI. Strong answers catch the disconnect exception, read its code attribute, and log 1000 for normal closures versus 1001/1006 for crashes.
How do you handle slow startup without blocking the FastAPI event loop?
It tests FastAPI lifespan events and event loop hygiene. Use an async lifespan to offload blocking model loading to a thread pool, track readiness with a global flag, and return 503 for early requests. Never block the event loop in startup handlers.
How do you authenticate a FastAPI WebSocket connection?
This tests WebSocket limits and FastAPI dependency injection. Pass the JWT via query parameter or cookie at handshake, validate it with Depends, and reject with HTTP 403 or 1008 close.
How do you handle a WebSocket client disconnect in FastAPI?
Cite installing websockets, Handling disconnections and multiple clients pattern, and Depends. know FastAPI needs explicit cleanup for multiple WebSocket clients. saying FastAPI auto-cleans dead sockets with no cleanup.
What are startup and shutdown events in FastAPI?
Tests app lifespan hooks and resource lifecycle. Startup creates DB pools before traffic arrives; shutdown closes them after the last request. These decorators are deprecated; prefer lifespan context managers. Red flag: per-request middleware.
How do you define a WebSocket endpoint in FastAPI?
Import WebSocket, use @app.websocket, await accept, receive_text, then send_text. async endpoint wiring and the accept-receive-send lifecycle. forgetting accept or treating it like a standard HTTP route.
How do you directly modify FastAPI's generated OpenAPI dictionary?
Tests deep FastAPI lifecycle knowledge. Override app.openapi: save the original, call it to get the dict, mutate it, cache on app.openapi_schema, and return. Red flag: rewriting /openapi.json in middleware or touching the schema cache directly.
How do you disable FastAPI docs but keep the OpenAPI schema?
Tests FastAPI constructor routing: docs_url, redoc_url, and openapi_url. Answer: pass docs_url=None and redoc_url=None while keeping openapi_url="/openapi.json", gated by env var. Red flag: middleware or manual route deletion instead of native configuration.
Add a custom x- field to a FastAPI path operation schema
Tests knowledge of FastAPI's built-in OpenAPI extension hook. Answer: cite the path operation decorator's extra-schema dict (OpenAPI Extra) to merge x-internal-id directly. Red flag: proposing manual JSON editing or schema post-processing.
How do you mark a FastAPI endpoint as deprecated?
This tests decorator-level OpenAPI configuration in FastAPI. Pass deprecated=True to the path operation decorator, e.g. @app.get("/old", deprecated=True), so Swagger UI shows a strikethrough. Red flag: burying a deprecation warning in the docstring instead.
How can you provide a Swagger UI example for a Pydantic body?
Tests whether you know FastAPI generates OpenAPI schema from Pydantic metadata. A strong answer names Field(example=...) for per-field samples and Body(example=...) for the full payload.
How do you document multiple response schemas in OpenAPI?
This tests FastAPI OpenAPI schema generation for error responses. A strong answer covers the decorator responses dict mapping status codes to Pydantic models and descriptions, plus manually returning JSONResponse with that code.
What are FastAPI's two default interactive documentation UIs and URL paths?
This tests whether you know FastAPI's built-in auto-generated docs. A strong answer names Swagger UI at /docs and ReDoc at /redoc, then notes the OpenAPI schema at /openapi.json. A weak answer confuses these with external tools or custom routes.
Add summary and description to a FastAPI endpoint for Swagger UI
This tests FastAPI path operation decorator configuration. Pass summary and description to @app.get, or use function docstring for description. A red flag is setting metadata inside the function body or confusing docs with Pydantic Field descriptions.
How do you add a title, description, and version to FastAPI auto-docs?
Tests if you know FastAPI's metadata kwargs for OpenAPI docs. Pass title, description, and version to the FastAPI() constructor; Swagger UI and ReDoc render them automatically.
How do router-level and app-level dependencies affect dependency override testing?
This tests FastAPI dependency hierarchy and test isolation. A strong answer states overrides are global to the app, so router-specific deps need scoped fixtures to prevent cross-test leaks. A red flag is claiming APIRouter has its own override registry.
How do you test FastAPI background tasks are enqueued correctly?
This tests mocking framework hooks without firing side effects. A great answer: mock BackgroundTasks or override its dependency, assert add_task got the right function and payload, and test the sender separately.
How would you use pytest fixtures to manage TestClient and mock dependencies?
Tests FastAPI test isolation and dependency overrides. Strong answer: function-scoped fixture yielding TestClient, mock injection via app.dependency_overrides, and teardown cleanup to prevent state leaks.
How do you test a FastAPI endpoint without real tokens?
Tests whether you know FastAPI's dependency override mechanism to isolate business logic from auth. A great answer describes using app.dependency_overrides to swap the auth Depends for a mock returning a fake user, then cleaning up after the test.
Get Python bites daily.
Five a day, five minutes, offline. With quizzes so it sticks.
Open testing — you’ll join as an early tester.