Skip to content
tezvyn:

Python

217 bites tagged Python — interview questions with model answers, and 60-second explainers.

Python & FastAPI3 min read

Custom Field Serialization with @field_serializer

@field_serializer is an exit-only adapter for one field: it reshapes data leaving the Pydantic model without changing internals. Use it to format decimals, mask secrets, or tweak datetimes for FastAPI JSON. Never use it for validation; it only runs on output.

Python & FastAPI2 min read

Per-Field Validation with @field_validator

@field_validator scrubs a single Pydantic field before it enters the model. Use it for rules like 'password must contain a digit' or 'port must exceed 1024'. It only sees one field at a time, so cross-field checks belong in a model validator instead.

Python & FastAPI2 min read

Serialize Pydantic Models with model_dump

model_dump turns a Pydantic model into a plain Python dict, bridging typed objects and JSON serializers in FastAPI endpoints. Call it when you need raw data before returning a response. Do not confuse it with model_dump_json, which emits a string, not a dict.

Python & FastAPI2 min read

Overriding FastAPI's OpenAPI Generator

FastAPI lets you swap app.openapi to reshape its generated schema without forking. Use this for vendor extensions, filtered operations, or merging external schemas. Forgetting to cache the result means every docs request rebuilds it and destroys performance.

Python & FastAPI2 min read

Testing FastAPI Lifespan Events

FastAPI lifespan events only run when TestClient is used as a context manager. Use this to test startup logic like DB pools before endpoints. Using TestClient(app) without with skips lifespan, leaving your app uninitialized and tests silently wrong.

Python & FastAPI2 min read

Async Path Operations in FastAPI

FastAPI path operations can be async, letting the server switch to other requests during I/O waits. Declare dependencies and sub-dependencies async when they await external calls.

Python & FastAPI2 min read

Python Async Context Managers

Async context managers let you await during setup and teardown. Use async with for database connections or streams where acquiring and releasing both need I/O. The footgun is applying @contextmanager to async cleanup, which cannot await and will crash.

MLOps & Infrastructure1 min read

Most LLM Apps Need Workflows Not Agent Frameworks

Most LLM apps ship faster and more reliably as deterministic workflows than autonomous agents. Plain Python with structured outputs and local functions beats CrewAI and LangGraph for debugging. Map control flow in code before importing any agent framework.

MLOps & Infrastructure2 min read

Why avoid global Python dependencies for ML, and how do containers help?

This probes environment isolation and reproducibility in ML. A strong answer cites global dependency conflicts, system library skew, and brittle environments; then notes containers freeze the full stack for deterministic deployment.

MLOps & Infrastructure2 min read

Walk me through essential Dockerfile commands for a reproducible Python ML environment

Tests your ability to containerize Python ML scripts reproducibly. A strong answer covers FROM with a pinned slim image, WORKDIR, COPY for requirements and code, RUN pip install, and CMD or ENTRYPOINT.

Data Science & Analytics2 min read

How do you fetch JSON from a REST API and parse it?

This tests practical fluency with HTTP mechanics and JSON deserialization. A strong answer names the method, URL, and headers; checks the status code; then parses with r.json() or json.loads. A red flag is skipping error handling or confusing GET with POST.

Data Science & Analytics2 min read

Process a 50GB CSV with only 16GB RAM

Chunk with read_csv chunksize, filter columns via usecols, downcast int64 to int32/int16, skip rows. Streaming aggregation under memory constraints. Loading everything into one DataFrame or using default dtypes.

Data Science & Analytics2 min read

Calculate total and average sales per region in pandas

Tests split-apply-combine fluency. A strong answer groups by Region then calls agg with a dict or named aggregation to return sum and mean of Sales_Amount together. Red flag: chaining separate groupby calls or looping rows manually.

Data Science & Analytics2 min read

What is vectorization in NumPy and pandas?

Tests if you know why NumPy operations beat Python loops via contiguous memory and C-level SIMD. A strong answer defines vectorization as array-wide operations without explicit loops, contrasts a ufunc to a for-loop, and cites interpreter overhead removal.

Data Science & Analytics2 min read

Most efficient way to convert list of dicts to pandas DataFrame

Tests knowledge of vectorized DataFrame construction versus slow row-wise assembly. Answer: pass the list directly to pd.DataFrame(data); C-backed and handles missing keys as NaN. Red flag: recommending loops with pd.concat or iterative DataFrame building.

Data Science & Analytics2 min read

Vectorization: Ditch the Python Loop

Vectorization means issuing one batch command to C-backed arrays instead of looping in Python. Use it for million-row DataFrames or matrix math. The footgun is treating apply() as vectorized, or silently materializing giant temporaries that exhaust RAM.

Python & FastAPI2 min read

ARQ for FastAPI: Async Background Tasks

ARQ lets your FastAPI app offload heavy work to background workers, keeping the API responsive. It's a task queue built for asyncio. Use it for slow tasks like sending emails or processing data. The footgun is using blocking task libraries with async code.

Python & FastAPI2 min read

asyncio Streams: High-Level Async Network I/O

asyncio Streams are like async file handles for the network. You get a reader/writer pair to await data, simplifying TCP clients and servers for basic protocols. The footgun: the default buffer limit is small; reading large data will fail unexpectedly.

Python & FastAPI2 min read

FastAPI's StreamingResponse: Send Data in Chunks

StreamingResponse sends data piece by piece, like a live broadcast, instead of sending a complete file all at once. This keeps your server's memory low for huge responses like file downloads, video streams, or live data from AI models.

Python & FastAPI2 min read

Pydantic: Reusable Validation with Annotated Types

Pydantic's `Annotated` attaches validation logic directly to a type, making it reusable. Define a custom type like `SquareNumber` once and apply it to any model field, ensuring consistent validation without repeating code.

Python & FastAPI2 min read

FastAPI: Validating Models with Pydantic's Field

Pydantic's `Field` adds guardrails directly to your data model's attributes. Use it to enforce constraints like string length (`max_length=50`) or numeric ranges (`gt=0`), making your models self-validating.

Python & FastAPI2 min read

Mangum: Run Python ASGI Apps on Serverless

Mangum is an adapter for running Python ASGI apps (like FastAPI) on serverless platforms like AWS Lambda. It translates serverless events into ASGI requests, letting you deploy existing async web apps without a rewrite.

Python & FastAPI2 min read

From Dev Server to Production: Running FastAPI with Workers

Your dev server is a single process. For production, you need a process manager to run multiple Uvicorn worker processes, handling concurrent requests and providing fault tolerance.

Python & FastAPI2 min read

Your First Python Dockerfile Blueprint

A Dockerfile is a recipe for building a self-contained environment for your Python app. Use it to ensure your app runs identically everywhere, from your laptop to production. The common footgun is forgetting a .dockerignore file, which bloats your image.

Get Python bites daily.

Five a day, five minutes, offline. With quizzes so it sticks.

Open testing — you’ll join as an early tester.