Python Core and FastAPI Interview Preparation
1. Python Core Fundamentals
Q1: What is FastAPI and what are its key features?
FastAPI is a modern, high-performance web framework for building APIs with Python 3.7+ based on standard Python type hints. It is designed to be easy to use, fast to code, and ready for production. Key features include:
- Fast: Very high performance, on par with NodeJS and Go (thanks to Starlette and Pydantic). One of the fastest Python frameworks available.
- Fast to code: Increase the speed to develop features by about 200% to 300%.
- Fewer bugs: Reduce about 40% of human (developer) induced errors.
- Intuitive: Great editor support. Completion everywhere. Less time debugging.
- Easy: Designed to be easy to use and learn. Less time reading documentation.
- Short: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.
- Robust: Get production-ready code. With automatic interactive documentation.
- Standards-based: Based on (and fully compatible with) the open standards for APIs: OpenAPI (previously known as Swagger) and JSON Schema.
FastAPI leverages Pydantic for data validation and Starlette for the web parts, making it extremely fast. It also supports asynchronous programming out of the box using async and await.
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
Q2: What is the difference between ASGI and WSGI?
WSGI (Web Server Gateway Interface) and ASGI (Asynchronous Server Gateway Interface) are specifications that describe how a web server communicates with a web application.
- WSGI: The traditional standard for Python web applications (like Django and Flask). It is synchronous by nature, meaning it handles one request at a time per worker process. It's not designed to handle long-lived connections like WebSockets.
- ASGI: The spiritual successor to WSGI. It is designed to provide a standard interface between async-capable Python web servers, frameworks, and applications. It supports both synchronous and asynchronous apps and can handle multiple protocol types including HTTP, HTTP2, and WebSockets.
FastAPI is an ASGI framework, which allows it to handle many concurrent connections efficiently using Python's asyncio.
# WSGI example (conceptual)
def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/plain')])
return [b"Hello World"]
# ASGI example (conceptual)
async def application(scope, receive, send):
await send({
'type': 'http.response.start',
'status': 200,
'headers': [[b'content-type', b'text/plain']],
})
await send({
'type': 'http.response.body',
'body': b"Hello World",
})
Q3: How does FastAPI use Pydantic?
FastAPI uses Pydantic for all data validation, serialization, and documentation. When you define a path operation function with parameters that are Pydantic models, FastAPI will:
- Read the request body as JSON.
- Convert the corresponding types (if necessary).
- Validate the data. If the data is invalid, it will return a clean and clear error.
- Give you the validated data in the parameter.
- Generate JSON Schema for the data, which is then used by the OpenAPI documentation.
This integration ensures that your API is type-safe and well-documented with minimal effort.
from fastapi import FastAPI
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
is_offer: bool = None
app = FastAPI()
@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
return {"item_name": item.name, "item_id": item_id}
Q4: What are Path Parameters in FastAPI?
Path parameters are components of the URL path that are used to identify a specific resource. In FastAPI, you declare path parameters with the same syntax used by Python format strings. You can also use Python type hints to specify the type of the parameter, and FastAPI will automatically validate and convert the value.
If you visit /items/3, the item_id will be the integer 3. If you provide a non-integer value, FastAPI will return an HTTP 422 error.
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
Q5: What are Query Parameters in FastAPI?
When you declare other function parameters that are not part of the path, they are automatically interpreted as "query" parameters. These are the key-value pairs that come after the ? in a URL, separated by &. Query parameters are optional by default if they have a default value, or required if they don't.
For example, in the URL /items/?skip=0&limit=10, the query parameters are skip with value 0 and limit with value 10.
from fastapi import FastAPI
app = FastAPI()
fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]
@app.get("/items/")
async def read_item(skip: int = 0, limit: int = 10):
return fake_items_db[skip : skip + limit]
Q6: How do you handle request bodies in FastAPI?
To receive a request body, you use Pydantic models. You define a class that inherits from pydantic.BaseModel and declare the data shape as attributes with type hints. Then, you add it as a parameter to your path operation function. FastAPI will automatically parse the JSON body, validate it against the model, and provide the instance to your function.
You can also use Body parameters for single values or complex configurations.
from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
app = FastAPI()
@app.post("/items/")
async def create_item(item: Item):
return item
Q7: What is the purpose of the uvicorn command?
Uvicorn is a lightning-fast ASGI server implementation, using uvloop and httptools. It is the recommended server for running FastAPI applications. Since FastAPI is just the framework, it needs an ASGI server to listen for network requests and pass them to the application code.
Common usage includes the --reload flag during development, which restarts the server whenever code changes are detected.
# Start the FastAPI app in main.py, object named app
uvicorn main:app --reload
Q8: How does FastAPI generate automatic documentation?
FastAPI automatically generates interactive API documentation (also known as a "UI") using OpenAPI standards. It provides two default options:
- Swagger UI: Accessible at
/docs. It allows you to interact with your API directly from the browser. - ReDoc: Accessible at
/redoc. It provides a clean, professional documentation layout.
This happens because FastAPI builds an internal OpenAPI schema based on your path operations, parameters, and Pydantic models.
# No extra code needed! Just run the app and go to /docs
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/")
async def read_items():
return [{"item_id": "Portal Gun"}]
Q9: What are "Type Hints" and why are they important in FastAPI?
Type hints (introduced in Python 3.5) allow you to specify the expected data type for variables, function parameters, and return values. FastAPI relies heavily on them to:
- Validate data: Check if the provided data matches the specified type.
- Convert data: Automatically convert strings from URLs/JSON to Python types (e.g., "5" to
int(5)). - Document the API: Include type information in the generated OpenAPI schema.
- Improve Developer Experience: Enable autocompletion and error checking in IDEs.
def get_full_name(first_name: str, last_name: str):
full_name = first_name.title() + " " + last_name.title()
return full_name
# FastAPI uses this info for validation!
Q10: How do you handle optional parameters in FastAPI?
Optional query parameters can be defined by providing a default value of None or using the Optional type hint from the typing module (or just | None in Python 3.10+). If a parameter has a default value, it's not required in the request.
from typing import Optional
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: str, q: Optional[str] = None):
if q:
return {"item_id": item_id, "q": q}
return {"item_id": item_id}
Q11: What is the app.include_router() method used for?
As an application grows, putting all path operations in a single file becomes unmanageable. APIRouter allows you to group related path operations into separate modules. You then use app.include_router() to plug these groups into the main FastAPI application. This facilitates a clean, modular project structure.
# In routers/items.py
from fastapi import APIRouter
router = APIRouter()
@router.get("/items/")
async def read_items(): ...
# In main.py
from fastapi import FastAPI
from .routers import items
app = FastAPI()
app.include_router(items.router)
Q12: How do you return a specific HTTP status code?
You can define the default status code for a path operation using the status_code parameter in the decorator. FastAPI also provides the status module which contains constants for all HTTP status codes, making your code more readable.
from fastapi import FastAPI, status
app = FastAPI()
@app.post("/items/", status_code=status.HTTP_201_CREATED)
async def create_item(name: str):
return {"name": name}
Q13: What is Dependency Injection in FastAPI?
Dependency Injection is a design pattern where an object receives other objects that it depends on. FastAPI has an extremely powerful and easy-to-use dependency injection system. It allows you to:
- Share logic (like database connections or security).
- Enforce security and authentication.
- Minimize code repetition.
You define a dependency as a function or class and use Depends() in your path operation parameters.
from typing import Optional
from fastapi import Depends, FastAPI
app = FastAPI()
async def common_parameters(q: Optional[str] = None, skip: int = 0, limit: int = 10):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/")
async def read_items(commons: dict = Depends(common_parameters)):
return commons
Q14: How do you handle form data in FastAPI?
To receive form fields instead of JSON, you use the Form class from fastapi. Since form data is usually encoded using application/x-www-form-urlencoded, you must install the python-multipart package. Each form field is declared as a parameter in your function.
from fastapi import FastAPI, Form
app = FastAPI()
@app.post("/login/")
async def login(username: str = Form(...), password: str = Form(...)):
return {"username": username}
Q15: How do you handle file uploads in FastAPI?
FastAPI allows you to define files to be uploaded by the client using File and UploadFile. UploadFile is preferred because it uses a temporary file on disk if the file is too large, saving memory, and it provides a file-like interface with metadata (like filename and content type).
from fastapi import FastAPI, File, UploadFile
app = FastAPI()
@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
return {"filename": file.filename}
Q16: What is the difference between async def and def in FastAPI?
async def: Used when you want to useawaitinside the function (for asynchronous operations like DB calls or network requests). FastAPI will run these functions in the main event loop.def: Used for synchronous logic. FastAPI will run these functions in a separate thread pool (to avoid blocking the event loop), ensuring that your app remains responsive.
Generally, use async def if you are using an async library, and def if you are using a blocking library (like standard requests or psycopg2).
@app.get("/async")
async def async_call():
# results = await some_async_lib.get()
return {"mode": "asynchronous"}
@app.get("/sync")
def sync_call():
# results = some_blocking_lib.get()
return {"mode": "synchronous"}
Q17: How do you handle errors and exceptions in FastAPI?
You can raise an HTTPException to return a specific HTTP status code and a detail message to the client. FastAPI also allows you to define custom exception handlers using the @app.exception_handler decorator, which lets you catch specific Python exceptions and return custom responses.
from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: str):
if item_id not in ["foo", "bar"]:
raise HTTPException(status_code=404, detail="Item not found")
return {"item": item_id}
Q18: What are "Middleware" in FastAPI?
Middleware is a function that works with every request before it is processed by any specific path operation, and also with every response before returning it. It's useful for:
- Logging.
- Adding custom headers.
- Process timing.
- CORS (Cross-Origin Resource Sharing).
import time
from fastapi import FastAPI, Request
app = FastAPI()
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
return response
Q19: How do you handle CORS in FastAPI?
CORS allows a browser to make requests to a different domain than the one that served the web page. FastAPI provides a CORSMiddleware that you can easily add to your application to specify allowed origins, methods, and headers.
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
Q20: What is the purpose of BaseModel in Pydantic?
BaseModel is the primary class used to define data structures in Pydantic. By inheriting from it, you define the fields and their types. Pydantic then provides:
- Validation: Checks that input data matches the types.
- Serialization: Converts the model instance into a dictionary or JSON string.
- Schema Generation: Creates a JSON Schema representation of the model.
from pydantic import BaseModel
class User(BaseModel):
id: int
username: str
email: str
is_active: bool = True
Q21: How do you perform data validation on path/query parameters?
FastAPI provides classes like Path, Query, Cookie, and Header to add metadata and validation to parameters. You can set constraints like minimum/maximum length for strings, or numerical ranges.
from fastapi import FastAPI, Query, Path
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
item_id: int = Path(..., title="The ID of the item", ge=1),
q: str = Query(None, min_length=3, max_length=50)
):
return {"item_id": item_id, "q": q}
Q22: What is a "Response Model" in FastAPI?
The response_model parameter in a path operation decorator allows you to define the Pydantic model used for the response. FastAPI will:
- Convert the output: Ensure the data returned matches the model.
- Filter data: Remove any fields not defined in the model (great for hiding passwords or internal IDs).
- Document the response: Include the response structure in the OpenAPI schema.
from pydantic import BaseModel
from fastapi import FastAPI
class UserIn(BaseModel):
username: str
password: str
class UserOut(BaseModel):
username: str
app = FastAPI()
@app.post("/user/", response_model=UserOut)
async def create_user(user: UserIn):
return user # password will be filtered out!
Q23: How do you use Security and OAuth2 in FastAPI?
FastAPI has built-in support for security and authentication. It provides utilities for OAuth2 (with Password flow, Bearer tokens, etc.), API keys, and HTTP Basic auth. You use OAuth2PasswordBearer to define the token URL and then use it as a dependency.
from fastapi import Depends, FastAPI
from fastapi.security import OAuth2PasswordBearer
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
@app.get("/users/me")
async def read_users_me(token: str = Depends(oauth2_scheme)):
return {"token": token}
Q24: What is Starlette?
Starlette is a lightweight ASGI framework/toolkit, which is ideal for building high-performance asyncio services. FastAPI is built directly on top of Starlette. It handles the low-level web details like routing, request/response handling, and WebSocket support, while FastAPI adds features like data validation, documentation, and dependency injection.
Q25: What is httptools?
httptools is a Python binding for the nodejs HTTP parser. It is used by Uvicorn to parse HTTP requests extremely quickly. This is one of the reasons why FastAPI/Uvicorn benchmarks are so high.
Q26: What is uvloop?
uvloop is a fast, drop-in replacement for the built-in asyncio event loop. It is implemented in Cython and uses libuv under the hood. Uvicorn uses uvloop by default if it's installed, making the event loop significantly faster.
Q27: How do you define a constant or a fixed set of values for a parameter?
You can use Python's Enum to define a set of allowed values. When you use an Enum as a type hint for a parameter, FastAPI will:
- Validate that the input is one of the Enum members.
- Show the available values in the interactive documentation (dropdown).
from enum import Enum
from fastapi import FastAPI
class ModelName(str, Enum):
alexnet = "alexnet"
resnet = "resnet"
lenet = "lenet"
app = FastAPI()
@app.get("/models/{model_name}")
async def get_model(model_name: ModelName):
return {"model_name": model_name}
Q28: How do you handle nested Pydantic models?
Pydantic allows you to use one model as a type for a field in another model. FastAPI handles these nested structures automatically, validating the entire tree and documenting it correctly in OpenAPI.
from typing import List, Optional
from pydantic import BaseModel
class Image(BaseModel):
url: str
name: str
class Item(BaseModel):
name: str
images: Optional[List[Image]] = None
Q29: What is the Body parameter used for?
When you have multiple Pydantic models in your function parameters, FastAPI expects each of them to be a key in a single JSON body. If you want FastAPI to expect the model's fields directly in the body, or if you want to receive a single raw value in the body, you use Body(...).
from fastapi import Body, FastAPI
from pydantic import BaseModel
class Item(BaseModel):
name: str
app = FastAPI()
@app.post("/items/")
async def update_item(item: Item, importance: int = Body(...)):
return {"item": item, "importance": importance}
Q30: How do you set up environment variables in FastAPI?
The standard way is to use a .env file and Pydantic's BaseSettings. This provides a type-safe way to manage configuration, with automatic reading from environment variables and validation.
from pydantic import BaseSettings
class Settings(BaseSettings):
app_name: str = "Awesome API"
admin_email: str
items_per_user: int = 50
class Config:
env_file = ".env"
settings = Settings()
Q31: What is the Request object in FastAPI?
While FastAPI usually hides the raw request details behind parameters, you can access the raw starlette.requests.Request object by declaring a parameter of that type. This is useful for accessing things like client IP, headers not covered by Header, or raw body bytes.
from fastapi import FastAPI, Request
app = FastAPI()
@app.get("/items/")
async def read_items(request: Request):
client_host = request.client.host
return {"client_host": client_host}
Q32: How do you use Background Tasks in FastAPI?
FastAPI provides a BackgroundTasks class that allows you to schedule a function to run after returning the response. This is perfect for tasks like sending emails or processing images that shouldn't delay the API response.
from fastapi import BackgroundTasks, FastAPI
app = FastAPI()
def write_notification(email: str, message=""):
with open("log.txt", mode="a") as log:
log.write(f"notification for {email}: {message}")
@app.post("/send-notification/{email}")
async def send_notification(email: str, background_tasks: BackgroundTasks):
background_tasks.add_task(write_notification, email, message="some notification")
return {"message": "Notification sent in the background"}
Q33: What is the StaticFiles class used for?
StaticFiles is used to serve static assets like images, CSS, or JavaScript files. You mount a directory to a specific path in your application.
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
Q34: How do you handle WebSockets in FastAPI?
FastAPI has native support for WebSockets through Starlette. You use the @app.websocket decorator and a WebSocket object to manage the connection, receiving and sending messages.
from fastapi import FastAPI, WebSocket
app = FastAPI()
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Message text was: {data}")
Q35: What is the purpose of TestClient?
TestClient (based on httpx) allows you to test your FastAPI application by making "requests" to it without actually running a server. This is the standard way to write unit and integration tests for your API.
from fastapi.testclient import TestClient
from .main import app
client = TestClient(app)
def test_read_main():
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"msg": "Hello World"}
Q36: How do you document multiple response examples?
In the path operation decorator, you can use the responses parameter to define additional status codes and provide examples or descriptions for each.
@app.get("/items/{item_id}", responses={404: {"description": "Item not found"}})
async def read_item(item_id: str):
if item_id == "foo":
return {"id": "foo", "value": "there goes my hero"}
raise HTTPException(status_code=404)
Q37: What is GzipMiddleware?
This middleware automatically compresses responses for any request that includes "gzip" in the Accept-Encoding header. This reduces the amount of data transferred over the network.
from fastapi.middleware.gzip import GzipMiddleware
app.add_middleware(GzipMiddleware, minimum_size=1000)
Q38: How do you handle JSON serialization of custom objects?
FastAPI uses the jsonable_encoder to convert data into a format that can be converted to JSON. If you have custom objects (like SQLAlchemy models), you can use this encoder to get a standard Python dict.
from fastapi.encoders import jsonable_encoder
from datetime import datetime
class MyObj:
def __init__(self, name):
self.name = name
self.created = datetime.now()
@app.get("/custom")
def get_custom():
obj = MyObj("test")
return jsonable_encoder(obj)
Q39: What is the alias parameter in Field, Query, etc.?
The alias parameter allows you to use a different name for a field in the API than the one used in your Python code. This is useful for handling hyphenated names (like user-agent) which are not valid Python variable names.
from fastapi import Query
@app.get("/items/")
async def read_items(q: str = Query(None, alias="item-query")):
return {"q": q}
Q40: What are "Sub-dependencies"?
A dependency can itself depend on other dependencies. FastAPI will resolve the entire dependency tree automatically, ensuring that every function gets exactly what it needs.
async def dep_a():
return "A"
async def dep_b(a: str = Depends(dep_a)):
return f"{a}B"
@app.get("/")
async def root(b: str = Depends(dep_b)):
return {"val": b}
Q41: How do you use yield in dependencies?
Dependencies with yield (introduced in FastAPI 0.30) allow you to run code after the path operation has finished. This is perfect for managing resources like database sessions or file handles, ensuring they are always closed.
async def get_db():
db = DBSession()
try:
yield db
finally:
db.close()
Q42: What is the lifespan event?
The lifespan event allows you to define logic that should run before the application starts up and after it shuts down. This is the modern replacement for @app.on_event("startup") and @app.on_event("shutdown").
from contextlib import asynccontextmanager
from fastapi import FastAPI
@asynccontextmanager
async def lifespan(app: FastAPI):
# Load the ML model
yield
# Clean up the ML model
Q43: How do you handle path parameters that contain paths?
If you have a path parameter that should match a sub-path (e.g., /files/images/logo.png), you can use the :path suffix in the parameter definition.
@app.get("/files/{file_path:path}")
async def read_file(file_path: str):
return {"file_path": file_path}
Q44: What is the Embed parameter in Body?
If you only have one Pydantic model in your body, but you want it to be expected as a key inside a JSON object (rather than the body itself), you use Body(..., embed=True).
@app.post("/items/")
async def update_item(item: Item = Body(..., embed=True)):
return {"item": item}
# Expects: {"item": {...}} instead of just {...}
Q45: How do you exclude a path from the OpenAPI schema?
You can set include_in_schema=False in the path operation decorator. The endpoint will still work, but it won't appear in /docs or /redoc.
@app.get("/internal", include_in_schema=False)
async def internal_route():
return {"msg": "secret"}
Q46: What is the Proxy Headers Middleware?
When running FastAPI behind a proxy (like Nginx or Traefik), the application might see the internal IP of the proxy instead of the real client IP. This middleware (available via Uvicorn) helps process headers like X-Forwarded-For to determine the actual client information.
Q47: How do you handle multiple files upload?
You can define a parameter as a List[UploadFile]. FastAPI will automatically handle multiple files sent in a single multipart form request.
from typing import List
@app.post("/uploadfiles/")
async def create_upload_files(files: List[UploadFile] = File(...)):
return {"filenames": [file.filename for file in files]}
Q48: What is httpx and why is it used with FastAPI?
httpx is a next-generation HTTP client for Python, supporting both sync and async requests. It is often used with FastAPI for making external API calls from within path operations, and it's also used by TestClient.
Q49: How do you customize the OpenAPI schema?
FastAPI allows you to override the openapi method of the application object to add custom metadata, tags, or security definitions to the generated schema.
def custom_openapi():
if app.openapi_schema:
return app.openapi_schema
openapi_schema = get_openapi(...)
app.openapi_schema = openapi_schema
return app.openapi_schema
app.openapi = custom_openapi
Q50: What is the importance of pydantic-settings?
In newer versions of Pydantic (v2+), the settings management was moved to a separate package called pydantic-settings. It is still the recommended way to handle configuration in FastAPI.
2. Functions, OOP, and Iteration
Q51: What is the difference between a class and an object?
A class is a blueprint. An object is an instance created from that blueprint.
class User:
def __init__(self, name):
self.name = name
u = User("Asha")
Q52: What are __init__, self, and instance attributes?
__init__ initializes a new object. self refers to the current instance. Instance attributes belong to a specific object.
class Item:
def __init__(self, name):
self.name = name
Q53: What is the difference between instance, class, and static methods?
Instance methods access self. Class methods access cls. Static methods behave like namespaced functions.
class A:
kind = "A"
@classmethod
def from_name(cls, name):
return cls()
@staticmethod
def helper(x):
return x * 2
Q54: What is inheritance in Python?
Inheritance lets one class reuse and extend another class.
class Animal:
def speak(self):
return "..."
class Dog(Animal):
def speak(self):
return "woof"
Q55: What is polymorphism?
Polymorphism means different objects can share the same interface while behaving differently.
for obj in [Dog(), Animal()]:
print(obj.speak())
Q56: What are __repr__ and __str__?
__repr__ is for debugging and should be unambiguous. __str__ is for user-friendly display.
class User:
def __repr__(self):
return "User(name='Asha')"
Q57: What is an iterator?
An iterator is an object that implements __iter__() and __next__().
nums = iter([1, 2, 3])
print(next(nums))
Q58: What is a generator?
A generator is a lazy iterator created with yield.
def count_up_to(n):
for i in range(n):
yield i
Q59: Why use generators?
They save memory and support streaming data processing.
total = sum(x for x in range(1_000_000))
Q60: What is a decorator?
A decorator is a function that wraps another function to extend behavior.
def log(fn):
def wrapper(*args, **kwargs):
print(fn.__name__)
return fn(*args, **kwargs)
return wrapper
Q61: Why use functools.wraps in decorators?
It preserves metadata like the function name, docstring, and signature-friendly attributes.
from functools import wraps
def log(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
return fn(*args, **kwargs)
return wrapper
Q62: What is a context manager?
It manages setup and cleanup with the with statement.
with open("file.txt") as f:
data = f.read()
Q63: How do you create a custom context manager?
Use __enter__ and __exit__, or contextlib.contextmanager.
from contextlib import contextmanager
@contextmanager
def managed():
print("enter")
try:
yield
finally:
print("exit")
Q64: What are dataclasses?
dataclasses reduce boilerplate for classes that mainly store data.
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
Q65: What is method resolution order (MRO)?
MRO defines the order Python uses to look up methods in inheritance hierarchies.
print(Dog.mro())
Q66: What are property and descriptors?
property lets methods behave like attributes. Descriptors are the lower-level protocol behind many attribute behaviors.
class Temp:
def __init__(self, c):
self._c = c
@property
def fahrenheit(self):
return self._c * 9 / 5 + 32
3. Memory, Performance, and Standard Library
Q67: How does Python manage memory?
Python uses reference counting plus a cyclic garbage collector to reclaim unreachable objects.
import gc
gc.collect()
Q68: What is the GIL?
The Global Interpreter Lock allows only one thread to execute Python bytecode at a time in CPython. It simplifies memory management, but limits CPU-bound thread parallelism.
Q69: When should you use threading vs multiprocessing?
Use threads for I/O-bound work. Use processes for CPU-bound work to bypass the GIL.
from multiprocessing import Process
from threading import Thread
Q70: What is asyncio?
asyncio is Python's asynchronous I/O framework built around an event loop, coroutines, and non-blocking operations.
import asyncio
async def main():
await asyncio.sleep(1)
Q71: What is the difference between a coroutine and a task?
A coroutine is an awaitable function result. A task schedules a coroutine to run on the event loop.
task = asyncio.create_task(main())
Q72: What is the event loop?
The event loop schedules and runs asynchronous tasks, handling I/O readiness and coroutine switching.
Q73: How do locks work in Python concurrency?
Locks protect shared state from concurrent access.
from threading import Lock
lock = Lock()
with lock:
shared.append(1)
Q74: What are queues used for?
Queues safely pass data between producers and consumers in threaded or async code.
from queue import Queue
q = Queue()
q.put(1)
Q75: What is the collections module useful for?
It provides specialized containers like Counter, defaultdict, deque, and OrderedDict.
from collections import Counter, defaultdict, deque
Q76: What are itertools used for?
They provide efficient iterator-building blocks like chain, product, and islice.
from itertools import chain, islice
Q77: What is functools.lru_cache?
It memoizes function results to speed up repeated calls with the same arguments.
from functools import lru_cache
@lru_cache(maxsize=128)
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
Q78: What is pathlib?
pathlib offers an object-oriented API for filesystem paths.
from pathlib import Path
path = Path("data") / "users.csv"
Q79: What is logging and why prefer it over print?
logging supports severity levels, structured output, handlers, and production-friendly control.
import logging
logging.basicConfig(level=logging.INFO)
logging.info("started")
Q80: What is json commonly used for?
The json module serializes and parses JSON payloads.
import json
data = json.loads('{"a": 1}')
Q81: What does copy vs deepcopy do?
copy makes a shallow copy. deepcopy recursively copies nested objects.
import copy
shallow = copy.copy([1, [2]])
deep = copy.deepcopy([1, [2]])
4. Advanced Python and Interview Topics
Q82: What is the difference between shallow and deep immutability concerns?
An object may be immutable at the top level but still contain mutable members. That matters when copying or sharing nested structures.
Q83: What are __slots__ used for?
__slots__ can reduce memory usage by preventing per-instance __dict__ creation.
class User:
__slots__ = ("name", "age")
Q84: What is a metaclass?
A metaclass controls class creation. It is an advanced tool used for frameworks and custom class behavior.
class Meta(type):
pass
class Model(metaclass=Meta):
pass
Q85: What are descriptors used for in practice?
They power properties, methods, and many validation frameworks. They let you customize attribute access.
Q86: What are type hints used for?
Type hints improve readability, IDE support, and static analysis. They do not enforce types at runtime by default.
def total(items: list[int]) -> int:
return sum(items)
Q87: What are TypedDict, Protocol, and Literal?
They are typing tools for better static contracts: TypedDict for dict shapes, Protocol for structural typing, and Literal for fixed allowed values.
from typing import TypedDict, Literal
class UserRow(TypedDict):
id: int
name: str
Q88: What is async context management?
It is the asynchronous version of with, using __aenter__ and __aexit__.
async with session:
...
Q89: What is cancellation in asyncio?
Tasks can be cancelled cooperatively, usually by raising asyncio.CancelledError inside the coroutine.
Q90: Why can blocking code hurt async applications?
Blocking calls freeze the event loop and prevent other tasks from running. Use async libraries or offload to threads.
await asyncio.to_thread(blocking_call)
Q91: How do you share context safely across async tasks?
Use contextvars for task-local context instead of global variables.
from contextvars import ContextVar
request_id = ContextVar("request_id")
Q92: What is the difference between __iter__ and __next__?
__iter__ returns an iterator. __next__ returns the next item or raises StopIteration.
Q93: What are common Python performance tuning techniques?
Use built-in functions, avoid unnecessary copies, prefer generators for streams, use efficient data structures, and profile before optimizing.
Q94: What is timeit used for?
It measures small code snippets accurately for micro-benchmarks.
from timeit import timeit
print(timeit("sum(range(1000))", number=1000))
Q95: What is pdb?
pdb is Python's interactive debugger.
import pdb; pdb.set_trace()
Q96: What are common causes of memory leaks in Python?
Reference cycles, cached objects that grow forever, global containers, and unclosed resources can all cause memory growth.
Q97: How does hashing relate to dicts and sets?
Dict and set membership relies on hashable keys. Objects used as keys should have stable __hash__ and __eq__ behavior.
key = (1, 2)
lookup = {key: "value"}
Q98: What is the sqlite3 module useful for?
It provides a lightweight embedded database for local storage, tests, and small apps.
import sqlite3
conn = sqlite3.connect("app.db")
Q99: What is the subprocess module used for?
It runs external commands and captures their output safely.
import subprocess
result = subprocess.run(["python", "-V"], capture_output=True, text=True)
Q100: What is the decimal module for?
It provides precise decimal arithmetic, useful for money and accounting.
from decimal import Decimal
price = Decimal("19.99")
Q101: What is the fractions module for?
It represents rational numbers exactly as numerator/denominator pairs.
from fractions import Fraction
print(Fraction(1, 3) + Fraction(1, 6))
Q102: What is re used for?
The re module handles regular expressions for pattern matching and text extraction.
import re
match = re.search(r"\d+", "order-123")
Q103: What is argparse used for?
It helps build command-line interfaces with typed arguments and automatic help text.
Q104: What is unittest versus pytest?
unittest is the standard library test framework. pytest is a popular third-party framework with a simpler style and richer tooling.
Q105: What is monkey patching?
Monkey patching changes behavior at runtime, usually by replacing functions or attributes. It is powerful but can make code harder to reason about.
Q106: What are ABC and abstract methods?
Abstract base classes define required methods for subclasses.
from abc import ABC, abstractmethod
class Repo(ABC):
@abstractmethod
def save(self):
pass
Q107: What is the multiprocessing module good for?
It runs work in separate processes, which can use multiple CPU cores.
Q108: How do you avoid circular imports?
Move imports inside functions, extract shared code into a third module, or reorganize modules to reduce tight coupling.
Q109: What is a common use of yield from?
It delegates to another iterable or generator cleanly.
def chain_all():
yield from [1, 2, 3]
Q110: What is the difference between sorted() and list.sort()?
sorted() returns a new list. list.sort() sorts in place and returns None.
Q111: What is zip() used for?
It combines multiple iterables element by element.
names = ["a", "b"]
ages = [1, 2]
print(list(zip(names, ages)))
Q112: What is enumerate() used for?
It provides index and value while iterating.
for i, value in enumerate(["x", "y"]):
print(i, value)
Q113: What is a good way to parse configuration in Python?
Use environment variables, argparse, or a settings library; keep configuration separate from business logic.
Q114: What is the relationship between bytes and strings?
str is Unicode text. bytes is raw binary data. Encode text to bytes and decode bytes to text.
raw = "hello".encode("utf-8")
text = raw.decode("utf-8")
Q115: What is memoryview?
It provides a zero-copy view over binary data, useful for performance-sensitive code.
Q116: What is the difference between eval and exec?
eval evaluates a single expression. exec can execute statements and blocks of code. Both are risky with untrusted input.
Q117: What is the best answer to "How do you optimize Python code?"?
Profile first, then improve the bottleneck with better algorithms, appropriate data structures, caching, fewer allocations, or parallelism when needed.
Q118: What is the difference between == None and is None?
Use is None for identity checks against None. It is the idiomatic and safer style.
Q119: What is a closure?
A closure is a function that remembers variables from its enclosing scope.
def make_adder(n):
def add(x):
return x + n
return add
Q120: What are namedtuple and dataclass compared to plain tuples?
They provide more readable field access and structured data handling than raw tuples.
Q121: What is the difference between help(), dir(), and vars()?
help() shows documentation, dir() lists attributes, and vars() shows an object's __dict__ when available.
Q122: How do you handle graceful shutdown in Python services?
Close resources in finally blocks, use context managers, and listen for termination signals to stop loops and workers cleanly.
Q123: What is the role of the standard library in Python interviews?
Strong Python developers should know common modules like collections, itertools, functools, pathlib, logging, json, datetime, subprocess, and asyncio because they solve real problems without extra dependencies.
Q124: What is datetime commonly used for?
It handles dates, times, time zones, and formatting.
from datetime import datetime, timezone
now = datetime.now(timezone.utc)
Q125: What is the difference between replace() and reassignment for immutable types?
Immutable types cannot be changed in place, so methods like string replace() return a new object.
Q126: What is a good pattern for CLI tools in Python?
Use argparse, pathlib, logging, and small composable functions; keep the command entrypoint thin.
Q127: What are common Python interview pitfalls?
Confusing identity with equality, mutating shared defaults, misunderstanding scope, blocking the event loop, and assuming threads bypass the GIL for CPU work.
Q128: What are Python's core built-in types?
The main built-in types are int, float, bool, str, bytes, list, tuple, set, frozenset, dict, and NoneType. Interviews often care more about mutability and semantics than memorizing the list.
values = [1, 1.5, True, "x", b"x", [1], (1,), {1}, frozenset({1}), {"a": 1}, None]
Behind the Question
This checks whether you understand Python's data model, mutability, and the difference between containers and scalars.
Red Flags
Mixing up str and bytes, or claiming all collections behave the same.
Q129: How does truthiness work in Python?
Python uses __bool__() first, then __len__() if __bool__ is missing. Empty containers, 0, 0.0, False, and None are falsy by default.
if []:
print("won't run")
if [1]:
print("runs")
Behind the Question
This tests whether you know how control flow decides between true and false values.
Red Flags
Assuming only True and False are valid booleans, or using == True unnecessarily.
Q130: What is the difference between is and ==?
== checks value equality. is checks object identity, meaning both names point to the same object.
a = [1, 2]
b = [1, 2]
print(a == b)
print(a is b)
Behind the Question
Identity is important for singleton checks like None, while equality is for comparing values.
Red Flags
Using is for strings, numbers, or custom value comparisons.
Q131: How does slicing work in Python?
Slicing uses start:stop:step, with stop excluded. Negative indexes count from the end, and slicing returns a new sequence.
nums = [0, 1, 2, 3, 4]
print(nums[1:4])
print(nums[::-1])
Behind the Question
This checks index boundaries, step behavior, and whether you know slices are non-destructive.
Red Flags
Forgetting that the stop index is exclusive.
Q132: What is unpacking in Python?
Unpacking assigns iterable values to multiple targets. It works with tuples, lists, and many iterables, including starred targets.
a, b = [1, 2]
first, *middle, last = [1, 2, 3, 4]
Behind the Question
This tests iterable handling and clean data extraction.
Red Flags
Forgetting that starred unpacking can capture variable-length portions.
Q133: What are list comprehensions used for?
They provide a concise way to build lists from iterables, often replacing simple loops.
squares = [x * x for x in range(5)]
Behind the Question
This checks whether you can express transformation logic idiomatically.
Red Flags
Using comprehensions for overly complex logic that hurts readability.
Q134: What is the difference between list comprehensions and generator expressions?
List comprehensions create the full list immediately. Generator expressions yield values lazily, which can save memory.
nums = [x for x in range(10)]
gen = (x for x in range(10))
Behind the Question
This tests memory awareness and lazy evaluation.
Red Flags
Saying generators are always faster or always better.
Q135: What is a generator in Python?
A generator is an iterator created by a function that uses yield. It produces values one at a time and preserves state between yields.
def count_up_to(n):
for i in range(n):
yield i
Behind the Question
This checks whether you understand lazy iteration and stateful resumption.
Red Flags
Treating a generator like a reusable list.
Q136: What is an iterator?
An iterator is an object with __iter__() and __next__(). It returns values until it raises StopIteration.
it = iter([1, 2, 3])
print(next(it))
Behind the Question
This tests the iteration protocol, which is central to many Python APIs.
Red Flags
Confusing iterables with iterators.
Q137: What is the difference between an iterable and an iterator?
An iterable can produce an iterator. An iterator is the object that actually yields items one by one.
items = [1, 2, 3]
it = iter(items)
Behind the Question
This is a common interview filter for understanding for loops and generators.
Red Flags
Assuming every iterable can be exhausted only once.
Q138: What are decorators in Python?
Decorators are callables that wrap or modify other callables, usually functions or methods.
def log(fn):
def wrapper(*args, **kwargs):
print(fn.__name__)
return fn(*args, **kwargs)
return wrapper
Behind the Question
This tests higher-order functions and behavior composition.
Red Flags
Forgetting to preserve metadata with functools.wraps.
Q139: Why is functools.wraps important?
It preserves the wrapped function's name, docstring, and other metadata, which helps debugging and introspection.
from functools import wraps
def log(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
return fn(*args, **kwargs)
return wrapper
Behind the Question
This checks whether you write production-quality decorators.
Red Flags
Returning a wrapper that hides the original function identity.
Q140: What is a context manager?
A context manager manages setup and cleanup around a block, usually via with and __enter__/__exit__.
with open("file.txt") as f:
data = f.read()
Behind the Question
This tests safe resource handling and deterministic cleanup.
Red Flags
Thinking with is only for files.
Q141: How do you create a custom context manager?
You can implement __enter__ and __exit__, or use contextlib.contextmanager for generator-based cleanup.
from contextlib import contextmanager
@contextmanager
def managed():
print("enter")
try:
yield
finally:
print("exit")
Behind the Question
This tests cleanup patterns for locks, files, and transactions.
Red Flags
Forgetting cleanup in exception paths.
Q142: What is exception propagation in Python?
When an exception is not handled, it bubbles up the call stack until it is caught or terminates the program.
try:
1 / 0
except ZeroDivisionError:
print("handled")
Behind the Question
This checks your understanding of error flow and control transfer.
Red Flags
Catching broad exceptions without intent.
Q143: When should you raise a custom exception?
Raise a custom exception when the caller needs a domain-specific failure mode that standard exceptions do not describe well.
class InvalidStateError(Exception):
pass
Behind the Question
This tests API design and error semantics.
Red Flags
Using custom exceptions for every minor branch.
Q144: What is the difference between except Exception and except BaseException?
Exception catches most application errors. BaseException also includes system-exiting exceptions like KeyboardInterrupt and SystemExit.
try:
risky()
except Exception:
handle()
Behind the Question
This checks whether you know which exceptions should usually be allowed to propagate.
Red Flags
Catching BaseException in normal application code.
Q145: What is a module in Python?
A module is a .py file containing Python code. Importing it executes the file once and creates a module object.
import math
print(math.pi)
Behind the Question
This tests basic import mechanics and namespace boundaries.
Red Flags
Assuming imports are just textual copies.
Q146: How do packages differ from modules?
A package is a collection of modules organized in a directory, usually with an __init__.py file, though namespace packages can exist without one.
from collections import defaultdict
Behind the Question
This tests how Python code is structured and discovered.
Red Flags
Treating directories and modules as interchangeable.
Q147: What is the purpose of __init__.py?
It marks a directory as a package in traditional packaging and can run package initialization code.
# package/__init__.py
Behind the Question
This checks whether you understand package import behavior.
Red Flags
Claiming __init__.py is always required in modern Python.
Q148: What is circular import and why is it a problem?
Circular imports happen when modules depend on each other during import time, which can leave names partially initialized.
# often fixed by moving imports inside functions
Behind the Question
This tests module design and dependency direction.
Red Flags
Suggesting circular imports are harmless because Python "figures it out".
Q149: What is class inheritance used for?
Inheritance lets one class reuse and specialize behavior from another class, but composition is often a better default.
class Animal:
def speak(self):
return "..."
class Dog(Animal):
def speak(self):
return "woof"
Behind the Question
This checks object-oriented modeling and reuse strategy.
Red Flags
Using inheritance where composition would be simpler.
Q150: What is the Method Resolution Order (MRO)?
MRO is the order Python uses to search for attributes and methods in class hierarchies.
print(Dog.mro())
Behind the Question
This tests multiple inheritance behavior and attribute lookup rules.
Red Flags
Ignoring super() behavior in multiple inheritance.
Q151: Why is super() important?
super() cooperates with the MRO so base classes can be chained correctly, especially in multiple inheritance.
class Child(Parent):
def __init__(self):
super().__init__()
Behind the Question
This tests cooperative inheritance and maintainable subclass design.
Red Flags
Calling base class methods directly in complex hierarchies.
Q152: What is object mutability?
Mutable objects can change in place, while immutable objects cannot.
items = [1]
items.append(2)
text = "a"
text += "b"
Behind the Question
This checks value semantics, reference behavior, and side effects.
Red Flags
Assuming assignment mutates an object.
Q153: How does Python memory management work at a high level?
Python uses reference counting and cyclic garbage collection. Objects are freed when no references remain, unless they are part of unreachable cycles.
import gc
gc.collect()
Behind the Question
This tests whether you understand object lifetime and leaks.
Red Flags
Believing Python has only one garbage collection strategy.
Q154: What is a reference cycle?
A reference cycle occurs when objects reference each other in a loop, preventing simple reference counting from freeing them immediately.
a = []
a.append(a)
Behind the Question
This checks whether you know why the cyclic GC exists.
Red Flags
Assuming cycles always leak forever.
Q155: Why are default mutable arguments dangerous?
Default mutable arguments are evaluated once, so the same object is reused across calls.
def add_item(item, bucket=None):
if bucket is None:
bucket = []
bucket.append(item)
return bucket
Behind the Question
This is one of the most common Python interview traps.
Red Flags
Using [] or {} as a function default.
Q156: What is the Global Interpreter Lock (GIL)?
The GIL allows only one thread to execute Python bytecode at a time in CPython, which limits CPU-bound threading scalability.
import threading
Behind the Question
This tests concurrency fundamentals and implementation awareness.
Red Flags
Saying threads always speed up CPU-heavy Python code.
Q157: When should you use threading?
Use threading for I/O-bound tasks such as network calls, file waits, or blocking APIs where concurrency matters more than CPU parallelism.
from threading import Thread
Behind the Question
This checks practical concurrency choices.
Red Flags
Using threads as the default answer for heavy computation.
Q158: When should you use multiprocessing?
Use multiprocessing for CPU-bound work when you want true parallelism across cores.
from multiprocessing import Pool
Behind the Question
This tests whether you know how to bypass the GIL for compute work.
Red Flags
Ignoring serialization overhead and process startup cost.
Q159: What is asyncio for?
asyncio provides an event loop for cooperative concurrency, especially useful for many concurrent I/O operations.
import asyncio
async def main():
await asyncio.sleep(1)
Behind the Question
This checks event-loop thinking and async control flow.
Red Flags
Calling blocking code directly inside async functions.
Q160: What is the difference between concurrency and parallelism?
Concurrency means handling multiple tasks in overlapping time. Parallelism means executing multiple tasks at the same instant.
# concurrency can be event-loop based; parallelism may use processes
Behind the Question
This is a core conceptual distinction in Python systems work.
Red Flags
Using the terms interchangeably.
Q161: What is a coroutine?
A coroutine is an async function or awaitable object that can pause and resume execution.
async def fetch():
return 1
Behind the Question
This tests understanding of async function behavior.
Red Flags
Confusing coroutine objects with the results they eventually produce.
Q162: What does await do?
await pauses the current coroutine until the awaited awaitable completes, letting the event loop run other tasks.
result = await some_async_call()
Behind the Question
This checks whether you understand cooperative scheduling.
Red Flags
Using await on non-awaitable objects.
Q163: What is the purpose of dataclasses?
Dataclasses reduce boilerplate for classes that mainly store data by generating methods like __init__ and __repr__.
from dataclasses import dataclass
@dataclass
class User:
name: str
age: int
Behind the Question
This tests modern Python data modeling.
Red Flags
Using dataclasses for classes with lots of custom behavior without considering clarity.
Q164: Why is field(default_factory=...) useful in dataclasses?
It creates a new default object for each instance, avoiding shared mutable defaults.
from dataclasses import dataclass, field
@dataclass
class Box:
items: list = field(default_factory=list)
Behind the Question
This checks whether you understand safe defaults in data containers.
Red Flags
Using [] directly as a dataclass field default.
Q165: What is a type hint in Python?
Type hints annotate expected types for readability, tooling, and static analysis, but Python does not enforce them at runtime by default.
def add(a: int, b: int) -> int:
return a + b
Behind the Question
This tests typing literacy and code clarity.
Red Flags
Treating annotations as runtime guarantees.
Q166: What are Protocols in typing?
Protocols describe structural subtyping: if an object has the required methods and attributes, it matches the protocol.
from typing import Protocol
class SupportsClose(Protocol):
def close(self) -> None: ...
Behind the Question
This tests interface design without inheritance coupling.
Red Flags
Assuming protocols require explicit inheritance.
Q167: What is collections.deque good for?
deque provides efficient appends and pops from both ends, making it useful for queues and sliding windows.
from collections import deque
q = deque([1, 2])
q.appendleft(0)
Behind the Question
This checks whether you know better alternatives to lists for queue-like workloads.
Red Flags
Using a list as a queue with frequent pop(0).
Q168: What is defaultdict?
defaultdict automatically creates default values for missing keys using a factory function.
from collections import defaultdict
counts = defaultdict(int)
counts["a"] += 1
Behind the Question
This tests convenient grouping and counting patterns.
Red Flags
Forgetting that the factory runs only for missing keys.
Q169: What is Counter used for?
Counter counts hashable items and supports common frequency-analysis operations.
from collections import Counter
print(Counter("mississippi"))
Behind the Question
This tests standard-library fluency for counting tasks.
Red Flags
Writing manual counting loops when Counter is simpler.
Q170: What does itertools provide?
itertools offers fast, memory-efficient iterator building blocks like chain, islice, product, and groupby.
from itertools import chain, islice
Behind the Question
This checks whether you can solve streaming problems cleanly.
Red Flags
Materializing large intermediate lists unnecessarily.
Q171: What is functools.lru_cache used for?
It caches function results for repeated calls with the same arguments, which can greatly improve performance for pure functions.
from functools import lru_cache
@lru_cache(maxsize=128)
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
Behind the Question
This tests caching strategy and memoization awareness.
Red Flags
Caching functions with side effects or unbounded memory growth.
Q172: What is functools.partial?
It creates a new callable with some arguments pre-filled.
from functools import partial
pow2 = partial(pow, exp=2)
Behind the Question
This checks composable function design.
Red Flags
Using partial when a small wrapper would be clearer.
Q173: What is pathlib preferred for?
pathlib provides object-oriented path handling that is usually clearer than string-based path manipulation.
from pathlib import Path
p = Path("data") / "file.json"
Behind the Question
This tests modern file path handling.
Red Flags
Manually concatenating paths with slashes.
Q174: What is the standard way to parse JSON in Python?
Use the json module to load JSON strings or files into Python objects and dump Python objects back to JSON.
import json
obj = json.loads('{"a": 1}')
text = json.dumps(obj)
Behind the Question
This checks core serialization knowledge.
Red Flags
Confusing JSON syntax with Python syntax.
Q175: What are regular expressions used for?
Regular expressions match, search, extract, and replace patterns in text.
import re
match = re.search(r"\d+", "abc123")
Behind the Question
This tests text processing fundamentals.
Red Flags
Using regex where plain string operations are simpler.
Q176: What is a common pitfall with regex in interviews?
A common pitfall is writing a pattern that works for one example but fails on edge cases like greedy matching, anchoring, or escaping.
re.findall(r"\w+", "a b")
Behind the Question
This checks careful pattern reasoning, not memorization.
Red Flags
Forgetting raw strings or overusing .*.
Q177: What is __slots__ used for?
__slots__ can reduce per-instance memory and prevent dynamic attribute creation by restricting allowed attributes.
class Point:
__slots__ = ("x", "y")
Behind the Question
This tests memory optimization awareness.
Red Flags
Using __slots__ without understanding inheritance tradeoffs.
Q178: What is __repr__ for?
__repr__ should return a developer-friendly representation, ideally one that is unambiguous and useful for debugging.
class User:
def __repr__(self):
return "User(name='a')"
Behind the Question
This checks object introspection and debugging quality.
Red Flags
Putting user-facing formatting in __repr__.
Q179: What is __iter__ used for?
__iter__ returns an iterator and lets custom objects work with for loops and other iteration tools.
class Bag:
def __iter__(self):
return iter(self.items)
Behind the Question
This tests how custom objects participate in Python protocols.
Red Flags
Returning a non-iterator from __iter__.
Q180: What is the purpose of __len__?
__len__ returns the logical size of an object and also affects truthiness when __bool__ is absent.
class Stack:
def __len__(self):
return len(self.items)
Behind the Question
This tests protocol integration and boolean behavior.
Red Flags
Returning negative or non-integer lengths.
Q181: What is the self parameter in methods?
self is the instance reference passed automatically to instance methods.
class A:
def f(self):
return self
Behind the Question
This checks basic object-oriented Python syntax.
Red Flags
Treating self as a keyword instead of a convention.
Q182: What is the difference between instance, class, and static methods?
Instance methods use self, class methods use cls, and static methods are namespaced functions tied to the class.
class A:
@classmethod
def make(cls):
return cls()
Behind the Question
This tests method binding and API design.
Red Flags
Using @staticmethod when class access is actually needed.
Q183: What is duck typing?
Duck typing means an object is acceptable if it behaves correctly, regardless of its concrete type.
def save(obj):
obj.write("x")
Behind the Question
This tests Python's structural, behavior-first style.
Red Flags
Overemphasizing inheritance over interface behavior.
Q184: What is the difference between shallow and deep copy?
A shallow copy duplicates the container but not nested objects. A deep copy recursively copies nested objects too.
import copy
shallow = copy.copy([[1]])
deep = copy.deepcopy([[1]])
Behind the Question
This checks nested mutability and object graphs.
Red Flags
Assuming list(x) or slicing copies nested data.
Q185: What is a frozen dataclass?
A frozen dataclass is immutable after creation, which can make instances safer and hashable when appropriate.
from dataclasses import dataclass
@dataclass(frozen=True)
class Config:
env: str
Behind the Question
This tests immutability and value-object design.
Red Flags
Mutating frozen objects by reaching around the API.
Q186: What is typing.Optional?
Optional[T] means T | None, indicating a value may be present or absent.
from typing import Optional
def find() -> Optional[str]:
return None
Behind the Question
This tests nullability semantics in typed code.
Red Flags
Using Optional when None is not actually allowed.
Q187: What is typing.Any?
Any disables static type checking for that value, so it should be used sparingly.
from typing import Any
Behind the Question
This checks whether you know how typing can be weakened.
Red Flags
Using Any everywhere to silence errors.
Q188: What is pathlib.Path.read_text() useful for?
It reads a text file directly from a Path object, making file I/O concise and readable.
from pathlib import Path
text = Path("notes.txt").read_text()
Behind the Question
This tests fluent stdlib usage.
Red Flags
Doing manual open/read/close for simple cases.
Q189: What is json.dumps(..., default=...) used for?
It lets you serialize non-standard objects by providing a fallback conversion function.
import json
json.dumps({"x": object()}, default=str)
Behind the Question
This tests customization of serialization behavior.
Red Flags
Assuming every object is JSON serializable by default.
Q190: What is the difference between map, filter, and list comprehensions?
map transforms items, filter selects items, and comprehensions can express both clearly in one syntax.
nums = [1, 2, 3]
evens = [x for x in nums if x % 2 == 0]
Behind the Question
This checks whether you can write readable functional-style code.
Red Flags
Using map/filter where comprehensions are clearer.
Q191: What is yield from good for?
It delegates part of a generator to another iterable or generator and forwards yielded values cleanly.
def chain_all():
yield from [1, 2, 3]
Behind the Question
This tests generator composition.
Red Flags
Not knowing that yield from can simplify nested generator logic.
Q192: How do you handle timeouts in concurrent Python code?
Use library-specific timeout options, asyncio.wait_for, or process/thread joins with a timeout depending on the concurrency model.
import asyncio
await asyncio.wait_for(task(), timeout=5)
Behind the Question
This tests production reliability under slow dependencies.
Red Flags
Relying on infinite waits and hoping tasks finish.
Q193: What is a race condition?
A race condition happens when program correctness depends on the timing of concurrent operations.
# shared mutable state without locks can race
Behind the Question
This checks awareness of concurrency hazards.
Red Flags
Assuming the GIL eliminates all races.
Q194: When do you need a lock?
Use a lock when multiple threads or tasks must safely update shared mutable state.
from threading import Lock
lock = Lock()
Behind the Question
This tests coordination of shared resources.
Red Flags
Protecting everything with locks instead of redesigning state flow.
Q195: What is the difference between threading.Lock and asyncio.Lock?
threading.Lock coordinates OS threads. asyncio.Lock coordinates coroutines on an event loop.
import asyncio
lock = asyncio.Lock()
Behind the Question
This tests choosing the right synchronization primitive.
Red Flags
Using thread locks inside async code without understanding blocking.
Q196: What is the purpose of collections.namedtuple?
It creates lightweight tuple-like objects with named fields.
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
Behind the Question
This tests familiarity with older but still common stdlib patterns.
Red Flags
Using namedtuple when a dataclass would be clearer.
Q197: What is __getattr__ used for?
It handles attribute lookup when the normal lookup fails, often for lazy access or dynamic proxies.
class Proxy:
def __getattr__(self, name):
return getattr(self.target, name)
Behind the Question
This tests dynamic attribute handling.
Red Flags
Confusing __getattr__ with __getattribute__.
Q198: What is the difference between __getattr__ and __getattribute__?
__getattribute__ intercepts every attribute access. __getattr__ only runs when normal lookup fails.
class A:
def __getattribute__(self, name):
return super().__getattribute__(name)
Behind the Question
This checks deep object model knowledge.
Red Flags
Implementing __getattribute__ without calling super() carefully.
Q199: What is __slots__ not good for?
It is not a universal optimization. It can complicate inheritance, serialization, and dynamic attribute use.
# use only when memory savings matter
Behind the Question
This tests judgment, not just features.
Red Flags
Applying __slots__ everywhere blindly.
Q200: How do Python imports cache modules?
Imported modules are cached in sys.modules, so the same module object is reused on later imports.
import sys
Behind the Question
This tests import semantics and initialization behavior.
Red Flags
Assuming re-import always re-executes module code.
Q201: What is the match statement used for?
Structural pattern matching provides a readable way to branch on shapes and values.
match value:
case [x, y]:
print(x, y)
Behind the Question
This tests familiarity with modern Python syntax.
Red Flags
Using match when a simple if is better.
Q202: What is the difference between staticmethod and a plain module function?
A static method lives on the class namespace, while a module function lives at module scope. Use whichever makes the API clearer.
class Math:
@staticmethod
def add(a, b):
return a + b
Behind the Question
This tests API organization choices.
Red Flags
Putting unrelated helpers on classes without purpose.
Q203: What is the nonlocal keyword for?
nonlocal lets an inner function rebind a variable from the nearest enclosing function scope.
def outer():
x = 0
def inner():
nonlocal x
x += 1
Behind the Question
This tests scope and closure mechanics.
Red Flags
Confusing nonlocal with global.
Q204: What is the global keyword for?
It allows a function to rebind a module-level variable.
count = 0
def inc():
global count
count += 1
Behind the Question
This tests scope handling and side effects.
Red Flags
Using globals as primary application state.
Q205: What is functools.reduce used for?
It cumulatively reduces an iterable to a single value using a binary function.
from functools import reduce
total = reduce(lambda a, b: a + b, [1, 2, 3])
Behind the Question
This checks functional programming fluency.
Red Flags
Using reduce when a loop or built-in is clearer.
Q206: What is a sentinel value?
A sentinel is a special placeholder object used to detect missing or default states unambiguously.
MISSING = object()
Behind the Question
This tests robust API design.
Red Flags
Using None as a sentinel when None is a valid value.
Q207: Why is object() useful as a sentinel?
Each call creates a unique object, so identity checks are reliable.
sentinel = object()
Behind the Question
This tests identity-safe placeholder usage.
Red Flags
Using strings or integers as sentinels without uniqueness guarantees.
Q208: What is the difference between bytes and bytearray?
bytes is immutable binary data. bytearray is mutable binary data.
data = bytearray(b"abc")
data[0] = 88
Behind the Question
This tests binary data handling and mutability.
Red Flags
Treating text and binary data as interchangeable.
Q209: What is memoryview good for?
It allows zero-copy access to binary buffers, which can improve performance when slicing or sharing data.
mv = memoryview(b"hello")
Behind the Question
This tests low-level performance awareness.
Red Flags
Using it where a normal bytes slice is fine.
Q210: What is a Protocol advantage over inheritance?
Protocols support structural typing, so unrelated classes can satisfy the same interface without a shared base class.
class Writer(Protocol):
def write(self, s: str) -> int: ...
Behind the Question
This tests flexible interface design.
Red Flags
Forcing inheritance just to satisfy typing.
Q211: What is typing.TypedDict used for?
It describes dictionaries with specific keys and value types for static checking.
from typing import TypedDict
class UserDict(TypedDict):
name: str
age: int
Behind the Question
This tests typed JSON-like data structures.
Red Flags
Assuming it enforces runtime validation.
Q212: What is contextlib.ExitStack useful for?
It manages a dynamic number of context managers and ensures all cleanup runs.
from contextlib import ExitStack
Behind the Question
This tests advanced resource management patterns.
Red Flags
Manually nesting many with statements when the number is dynamic.
Q213: What is itertools.groupby used for?
It groups consecutive equal keys, so the input often needs sorting first.
from itertools import groupby
Behind the Question
This tests whether you understand iterator-based grouping semantics.
Red Flags
Assuming it groups all identical values regardless of order.
Q214: What is the difference between sorted and heapq?
sorted orders an entire collection. heapq is better when you only need repeated access to the smallest or largest elements.
import heapq
Behind the Question
This tests algorithmic choice for ordering problems.
Red Flags
Using full sorting when a heap is more efficient.
Q215: What is re.compile for?
It precompiles a regular expression for repeated use and can make code clearer and sometimes faster.
import re
pattern = re.compile(r"\d+")
Behind the Question
This tests regex efficiency and reuse.
Red Flags
Compiling complex regexes inside tight loops.
Q216: What is a common pitfall with re.match?
re.match checks only from the beginning of the string, while re.search scans anywhere.
re.search(r"foo", "xxfooyy")
Behind the Question
This tests careful API selection.
Red Flags
Using match when you intended substring search.
Q217: What is the purpose of json.loads versus json.load?
loads parses a JSON string. load parses from a file-like object.
import json
Behind the Question
This tests basic I/O and serialization APIs.
Red Flags
Mixing up string and file-based APIs.
Q218: What is the purpose of pathlib.Path.exists()?
It checks whether the path exists in the filesystem.
from pathlib import Path
Path("x.txt").exists()
Behind the Question
This tests file system safety before I/O.
Red Flags
Assuming existence checks eliminate race conditions completely.
Q219: What is a closure pitfall in loops?
Functions defined in a loop can capture the same variable by reference, causing late-binding surprises.
funcs = [lambda x=i: x for i in range(3)]
Behind the Question
This tests variable capture semantics.
Red Flags
Assuming each lambda captures a copy of the loop variable.
Q220: What is late binding?
Late binding means a free variable is looked up when the inner function is called, not when it is defined.
def make():
x = 1
def inner():
return x
Behind the Question
This tests closure timing.
Red Flags
Ignoring how closures interact with mutation and loops.
Q221: What is a descriptor?
A descriptor is an object that customizes attribute access via methods like __get__, __set__, or __delete__.
class Descriptor:
def __get__(self, obj, objtype=None):
return 42
Behind the Question
This tests advanced object model knowledge.
Red Flags
Claiming properties are unrelated to descriptors.
Q222: What is @property built on?
@property uses the descriptor protocol to present method logic as attribute access.
class A:
@property
def value(self):
return 1
Behind the Question
This tests how Python exposes computed attributes.
Red Flags
Using properties for expensive work without caching or intent.
Q223: What is collections.ChainMap used for?
It combines multiple mappings into one logical view, useful for layered configuration.
from collections import ChainMap
Behind the Question
This tests map composition patterns.
Red Flags
Mutating the combined view without understanding the underlying maps.
Q224: What is sys.path?
It is the list of directories Python searches for imports.
import sys
print(sys.path)
Behind the Question
This tests import resolution basics.
Red Flags
Editing sys.path as a long-term architecture fix.
Q225: What is __name__ == "__main__" for?
It lets a file run as a script while preventing code from running on import.
if __name__ == "__main__":
main()
Behind the Question
This tests script/module dual-use patterns.
Red Flags
Putting top-level side effects in importable modules.
Q226: What is asyncio.gather used for?
It runs multiple awaitables concurrently and collects their results.
results = await asyncio.gather(task1(), task2())
Behind the Question
This tests async concurrency orchestration.
Red Flags
Ignoring failure behavior and cancellation semantics.
Q227: What is asyncio.create_task used for?
It schedules a coroutine to run concurrently on the event loop.
task = asyncio.create_task(work())
Behind the Question
This tests task scheduling and fire-and-forget patterns.
Red Flags
Creating tasks without tracking errors or cancellation.
Q228: Why should blocking I/O be avoided in async code?
Blocking I/O stops the event loop from making progress on other tasks, defeating async concurrency.
# use async-compatible clients when possible
Behind the Question
This tests whether you can preserve throughput in async services.
Red Flags
Calling time.sleep() inside async def.
Q229: What is the purpose of time.sleep versus asyncio.sleep?
time.sleep blocks the current thread. asyncio.sleep suspends a coroutine without blocking the event loop.
await asyncio.sleep(1)
Behind the Question
This tests basic async hygiene.
Red Flags
Using the blocking sleep in async code.
Q230: What is the difference between fork and spawn in multiprocessing?
fork copies the current process state. spawn starts a fresh interpreter process. The choice affects portability and safety.
import multiprocessing as mp
Behind the Question
This tests process startup semantics.
Red Flags
Assuming process behavior is identical across platforms.
Q231: What is serialization overhead in multiprocessing?
Data sent between processes must be pickled and unpickled, which can be expensive for large objects.
import pickle
Behind the Question
This tests performance tradeoffs of process boundaries.
Red Flags
Ignoring transfer costs when parallelizing small tasks.
Q232: What is pickling?
Pickling is converting Python objects into a byte stream for storage or transport, usually through pickle.
import pickle
data = pickle.dumps({"a": 1})
Behind the Question
This tests object persistence and IPC basics.
Red Flags
Using pickle with untrusted data.
Q233: Why is pickle dangerous with untrusted input?
Unpickling can execute arbitrary code, so it must never be used on untrusted data.
# never unpickle untrusted bytes
Behind the Question
This tests security awareness.
Red Flags
Treating pickle like safe JSON.
Q234: What is reprlib useful for?
It creates truncated representations of large objects, which can help in debugging without overwhelming output.
import reprlib
Behind the Question
This tests debugging tools in the standard library.
Red Flags
Printing huge nested objects blindly.
Q235: What is typing.Protocol often better than in interviews?
It is often better than a large inheritance tree when you want explicit interfaces without rigid coupling.
class Reader(Protocol):
def read(self) -> str: ...
Behind the Question
This tests modern interface design.
Red Flags
Equating interfaces only with abstract base classes.
Q236: What is the best way to answer questions about Python performance?
Start with algorithmic complexity, then mention data structures, I/O patterns, object allocations, profiling, and concurrency where relevant.
# profile first, optimize the bottleneck
Behind the Question
This tests whether your optimization answer is disciplined rather than speculative.
Red Flags
Jumping straight to micro-optimizations.
Q237: What is the most common senior-level Python pitfall?
Assuming Python syntax knowledge equals Python mastery. Strong answers show understanding of mutability, scoping, iteration, concurrency, object model behavior, and standard library tools.
def answer():
return "understand semantics, not just syntax"
Behind the Question
This checks whether you can explain Python in terms of behavior and tradeoffs.
Red Flags
Giving framework-specific answers when the question is about Python itself.
5. FastAPI Basic Questions
Q238: Explain the difference between Concurrency and Parallelism in the context of FastAPI.
- Concurrency: Handling multiple tasks by interleaving their execution. In FastAPI, this is achieved using
asyncio. When a request is waiting for I/O (like a DB query), the event loop switches to handle another request. This allows one worker process to handle many thousands of concurrent connections. - Parallelism: Running multiple tasks at the exact same time. This requires multiple CPU cores. To achieve parallelism in FastAPI, you typically run multiple Uvicorn worker processes (using the
--workersflag). Each worker process has its own event loop and can run on a different CPU core.
FastAPI is highly concurrent out of the box. For CPU-bound tasks that require parallelism, you might offload them to a task queue like Celery.
Q239: How does FastAPI handle blocking I/O calls in def functions?
If you define a path operation with def instead of async def, FastAPI knows it might be a blocking call. To prevent this from freezing the main event loop (which handles all other async requests), FastAPI runs these def functions in a separate internal thread pool (using anyio). This allows the event loop to continue processing other requests while the blocking call finishes in the background.
import time
@app.get("/blocking")
def blocking_call():
time.sleep(5) # This won't block the whole API!
return {"message": "done"}
Q240: Describe the lifecycle of a request in FastAPI.
- Socket Reception: Uvicorn (the ASGI server) receives the bytes from the network socket.
- Parsing: Uvicorn parses the raw bytes into an ASGI "scope" and "receive" callable.
- Application Entry: Uvicorn calls the FastAPI application object.
- Middleware (Request Phase): Any registered middleware processes the request.
- Routing: FastAPI's router matches the URL and method to a path operation.
- Dependency Resolution: FastAPI resolves all dependencies (and sub-dependencies) required by the function.
- Validation: FastAPI validates path, query, header, and body parameters using Pydantic.
- Execution: The path operation function is called (in the event loop if
async def, or in a thread pool ifdef). - Response Creation: The return value is encoded into a response object.
- Middleware (Response Phase): Middleware processes the response.
- Background Tasks: Any scheduled background tasks are executed.
- Socket Send: Uvicorn sends the response bytes back to the client.
Q241: How do you implement "Dependency Overrides" for testing?
When testing, you often want to replace real dependencies (like a database connection) with mocks or test-specific versions. FastAPI's app.dependency_overrides dictionary allows you to map a dependency function to a replacement function. This makes it incredibly easy to inject test doubles without changing any application code.
from fastapi.testclient import TestClient
from .main import app, get_db
async def override_get_db():
try:
db = TestingSessionLocal()
yield db
finally:
db.close()
app.dependency_overrides[get_db] = override_get_db
client = TestClient(app)
Q242: What are the advantages of using UploadFile over bytes or File?
- Memory Efficiency:
bytesreads the entire file into memory.UploadFileuses aSpooledTemporaryFile, which stays in memory up to a certain size limit and then rolls over to disk. This prevents your server from crashing on large uploads. - Metadata:
UploadFileprovides easy access to the filename, content type, and other headers. - File-like interface: It provides methods like
read(),write(),seek(), andclose(), making it compatible with many libraries that expect a file-like object. - Async support: It supports async read/write operations.
Q243: How do you implement global dependencies in FastAPI?
If you want a dependency to run for every path operation in your application (or a specific router), you can pass a list of Depends() objects to the FastAPI constructor or the include_router() method. This is useful for authentication or logging that must apply everywhere.
from fastapi import FastAPI, Depends, Header, HTTPException
async def verify_token(x_token: str = Header(...)):
if x_token != "fake-super-secret-token":
raise HTTPException(status_code=400, detail="X-Token header invalid")
app = FastAPI(dependencies=[Depends(verify_token)])
Q244: Explain how APIRouter helps in organizing large applications.
APIRouter acts as a "mini FastAPI" object. You can define path operations, dependencies, and middleware on a router. Then, you "include" it in the main app. This allows you to:
- Split code into logical modules (e.g.,
users.py,items.py). - Apply prefixes to all routes in a router (e.g.,
/users). - Apply tags to routes for better documentation grouping.
- Apply specific dependencies to all routes in a router (e.g., require login for all
/adminroutes).
# routers/users.py
router = APIRouter(prefix="/users", tags=["users"])
@router.get("/")
async def read_users(): ...
# main.py
app.include_router(users.router)
Q245: How do you handle recursive models in Pydantic?
If you have a model that refers to itself (like a category that has sub-categories), you need to use the update_forward_refs() method (in Pydantic v1) or just use the type itself if using Python 3.10+ stringized annotations. This tells Pydantic to resolve the string names into actual classes after they have all been defined.
from __future__ import annotations
from typing import List, Optional
from pydantic import BaseModel
class Category(BaseModel):
name: str
subcategories: List[Category] = []
Category.update_forward_refs()
Q246: What is the role of anyio in FastAPI?
FastAPI uses anyio to provide a consistent, high-performance interface for asynchronous networking and concurrency, regardless of whether the underlying event loop is asyncio or trio. Specifically, FastAPI uses anyio.to_thread.run_sync to run synchronous def functions in a way that doesn't block the event loop.
Q247: How do you implement custom validation for a Pydantic field?
You can use the @validator decorator (Pydantic v1) or the @field_validator decorator (Pydantic v2) in your model class. These methods receive the value of the field and can check it against custom logic, raising a ValueError if validation fails.
from pydantic import BaseModel, validator
class User(BaseModel):
username: str
@validator('username')
def username_alphanumeric(cls, v):
assert v.isalnum(), 'must be alphanumeric'
return v
Q248: Explain the use of OAuth2PasswordRequestForm.
This is a convenience dependency class provided by FastAPI. When used as a parameter, it automatically parses the body of a request sent as application/x-www-form-urlencoded (the standard for OAuth2 login forms) and extracts the username, password, and optional scope and client_id/secret.
from fastapi.security import OAuth2PasswordRequestForm
@app.post("/token")
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
return {"access_token": form_data.username, "token_type": "bearer"}
Q249: How do you stream a response in FastAPI?
You can return a StreamingResponse, which takes a generator (either sync or async). This is used for sending large files or real-time data streams where you don't want to load everything into memory at once.
from fastapi.responses import StreamingResponse
async def fake_video_streamer():
for i in range(10):
yield b"frame"
await asyncio.sleep(1)
@app.get("/video")
async def video_endpoint():
return StreamingResponse(fake_video_streamer())
Q250: What is the purpose of FileResponse?
FileResponse is a specialized response class for sending files. It handles headers like Content-Disposition (for filename) and uses efficient OS-level calls (like sendfile) if the server supports it, making file downloads very fast and efficient.
from fastapi.responses import FileResponse
@app.get("/download")
async def download_file():
return FileResponse("path/to/file.pdf", filename="awesome.pdf")
Q251: How do you handle security dependencies that require specific "Scopes"?
OAuth2 allows you to define "scopes" to limit what a token can do. In FastAPI, you use Security() instead of Depends() to declare a dependency and pass a list of required scopes. The dependency function can then check the scopes associated with the provided token.
from fastapi import Security
from fastapi.security import OAuth2PasswordBearer, SecurityScopes
@app.get("/items/")
async def read_items(token: str = Security(oauth2_scheme, scopes=["items:read"])):
return [{"item": "foo"}]
Q252: Explain the Config class inside a Pydantic model.
The Config class (or model_config in v2) is used to configure how Pydantic handles the model. Common settings include:
orm_mode = True: Allows Pydantic to read data from ORM objects (like SQLAlchemy) using dot notation instead of just dictionaries.allow_population_by_field_name = True: Allows using aliases when creating an instance.extra = 'forbid': Prevents creating models with extra fields not defined in the schema.
Q253: How do you implement "Sub-applications" in FastAPI?
You can mount a completely separate FastAPI application instance onto a path of your main application. The sub-app has its own documentation, routers, and dependencies. This is useful for splitting a massive project into independent services that share the same process.
subapi = FastAPI()
@subapi.get("/hello")
def read_sub(): return {"msg": "subapp"}
app = FastAPI()
app.mount("/sub", subapi)
Q254: What is Response and when would you use it directly?
While you usually return dictionaries or models, you can return a fastapi.Response object directly. This gives you full control over the response body, status code, and headers. You might use it to set custom cookies, return non-standard content types, or when a library generates the response for you.
from fastapi import Response
@app.get("/legacy")
def get_legacy_data():
data = "raw string"
return Response(content=data, media_type="text/plain")
Q255: How do you create a custom Response class?
You can inherit from fastapi.responses.Response and override the render method. FastAPI includes several built-in ones like JSONResponse, HTMLResponse, ORJSONResponse (for extreme speed), and UJSONResponse.
import orjson
from fastapi.responses import JSONResponse
class MyFastJSONResponse(JSONResponse):
def render(self, content):
return orjson.dumps(content)
Q256: Explain "Dependency Yield" and how it helps with DB sessions.
By using yield in a dependency, the code before the yield runs before the path operation, and the code after the yield runs after. This is perfect for database sessions: you open the session, yield it to the function, and then ensure it's closed in a finally block, even if an error occurred during the request.
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
Q257: How do you use HTTPBasic authentication?
HTTPBasic is a simple authentication scheme where the client sends a Base64 encoded username and password in the Authorization header. FastAPI provides a utility to parse this header and return an HTTPBasicCredentials object.
from fastapi.security import HTTPBasic, HTTPBasicCredentials
security = HTTPBasic()
@app.get("/users/me")
def read_current_user(credentials: HTTPBasicCredentials = Depends(security)):
return {"username": credentials.username}
Q258: Describe how to use APIRouter tags and metadata.
When creating an APIRouter, you can provide tags, responses, and dependencies. These will be automatically applied to every path operation defined on that router. This is much cleaner than repeating the same configuration for every endpoint.
Q259: What are "Param Functions" in FastAPI?
These are functions like Query(), Path(), Body(), Form(), File(), Header(), and Cookie(). They are used to define extra validation and metadata for function parameters. They return objects that FastAPI uses to build the OpenAPI schema and perform validation.
Q260: How do you use HTTPSRedirectMiddleware?
This middleware ensures that all incoming requests use HTTPS. If a request comes in over HTTP, it will be redirected to the HTTPS equivalent.
from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware
app.add_middleware(HTTPSRedirectMiddleware)
Q261: Explain the concept of Event Loops in the context of ASGI servers.
The event loop is the heart of an asynchronous application. It's a loop that waits for events (like a network packet arriving) and then executes the corresponding callback. ASGI servers like Uvicorn use an event loop (usually uvloop) to handle thousands of connections simultaneously. When your async def function awaits, it yields control back to the loop, allowing it to handle other events.
Q262: How do you handle huge request bodies efficiently?
If you are expecting very large bodies (like multi-GB uploads), you should use UploadFile as it handles streaming to disk. If you need to process raw bytes without loading everything into memory, you can use request.stream() to read chunks of the body.
Q263: What is the TrustedHostMiddleware?
This middleware prevents HTTP Host Header attacks by checking that the Host header of incoming requests matches a list of allowed patterns. If it doesn't, it returns a 400 error.
from fastapi.middleware.trustedhost import TrustedHostMiddleware
app.add_middleware(TrustedHostMiddleware, allowed_hosts=["example.com", "*.example.com"])
Q264: How do you define multiple examples for a single Pydantic model?
In Pydantic v2, you use the json_schema_extra parameter in the Config class or Field. You can provide a examples list that will be shown in the Swagger documentation.
class Item(BaseModel):
name: str
model_config = {
"json_schema_extra": {
"examples": [{"name": "Foo"}, {"name": "Bar"}]
}
}
Q265: What is ORJSONResponse and why would you use it?
ORJSONResponse uses the orjson library, which is a fast, correct JSON library for Python. It is significantly faster than the standard json module and supports more types (like dataclasses and UUIDs) out of the box. Use it for APIs where JSON serialization performance is a bottleneck.
Q266: How do you implement "API Versioning" in FastAPI?
The common ways are:
- Path Versioning:
/v1/users,/v2/users. Easy to implement usingAPIRouterprefixes. - Header Versioning: Client sends an
X-API-Versionheader. You can handle this using a dependency that reads the header. - Accept Header Versioning: Using media types like
application/vnd.myapi.v1+json.
Path versioning is usually preferred for its simplicity and visibility.
Q267: How do you document a response as a list of objects?
You use the List type hint from typing (or list in 3.9+) in the response_model parameter.
@app.get("/items/", response_model=List[Item])
async def read_items():
return [{"name": "item1"}, {"name": "item2"}]
Q268: What is the purpose of HTTPException vs a standard Python Exception?
HTTPException is specifically designed to be caught by FastAPI and converted into an HTTP response with a status code and detail message. Raising a standard Exception will result in an HTTP 500 (Internal Server Error) unless you have a custom exception handler defined for it.
Q269: How do you use Path parameters with regex validation?
The Path class has a regex (or pattern in newer versions) parameter that allows you to specify a regular expression that the parameter value must match.
@app.get("/items/{item_id}")
async def read_item(item_id: str = Path(..., pattern="^item-[0-9]+$")):
return {"item_id": item_id}
Q270: Explain the exclusive_start and exclusive_end in numerical validation.
In Query or Path, gt (greater than) and lt (less than) represent exclusive boundaries. ge (greater than or equal) and le (less than or equal) represent inclusive boundaries.
Q271: How do you define a response with multiple possible status codes?
You define the main status_code in the decorator, and then use the responses parameter to document the others. To actually return a different status code, you use an HTTPException or return a Response object with that status.
Q272: What is the Proxy pattern in FastAPI dependencies?
This refers to a dependency that returns another object (like a service or a client) that is configured based on the request (e.g., using a specific tenant ID from a header). This allows the path operation to just use the "proxy" without worrying about how it was created.
Q273: How do you use TestClient with WebSockets?
TestClient provides a websocket_connect context manager that allows you to simulate a WebSocket connection, sending and receiving messages to test your endpoint logic.
def test_websocket():
with client.websocket_connect("/ws") as websocket:
websocket.send_text("Hello")
data = websocket.receive_text()
assert data == "Message text was: Hello"
Q274: What is the ProxyFix middleware?
This is a middleware (often from the werkzeug library, but applicable in concept) used to fix headers when running behind multiple proxies. In the ASGI world, Uvicorn's --proxy-headers flag handles the basics of this.
Q275: How do you handle circular imports in a large FastAPI project?
- Move shared models to a separate
models.pyfile. - Use
APIRouterto keep routing logic separate from the main app creation. - Use string type hints or
from __future__ import annotations. - Import within functions (lazy imports) if absolutely necessary.
Q276: What is the difference between Form and Body?
Body: Expects data encoded asapplication/json.Form: Expects data encoded asapplication/x-www-form-urlencodedormultipart/form-data. You cannot use both in a single request because they use different encoding methods for the body.
Q277: How do you set a cookie in a FastAPI response?
You can use the set_cookie method on the Response object. You can either use the response parameter in your function (FastAPI will inject it) or return a Response object directly.
@app.post("/login")
def login(response: Response):
response.set_cookie(key="session_id", value="fake_id", httponly=True)
return {"msg": "logged in"}
Q278: Explain the concept of "Dependency Scoping".
In FastAPI, dependencies are resolved once per request. If multiple functions in the dependency tree depend on the same function, that function is executed only once, and the result is cached for the duration of the request. You can disable this behavior using use_cache=False in Depends().
Q279: How do you use Query parameters that are a list of values?
You define the type hint as List[str] (or your desired type). FastAPI will then expect multiple values for that key in the query string (e.g., ?q=foo&q=bar).
@app.get("/items/")
async def read_items(q: List[str] = Query([])):
return {"q": q}
Q280: What is the root_path parameter in FastAPI?
root_path is used when your application is running behind a proxy that prefixes the URL path (e.g., proxying /api/v1 to your app's /). It tells FastAPI to adjust the generated OpenAPI URLs and redirect paths accordingly.
Q281: How do you handle custom media types?
You can define the media_type in your Response or ResponseModel. To receive custom media types, you might need to read the raw Request.body() and parse it yourself.
Q282: What is the difference between Pydantic v1 and v2 in FastAPI?
Pydantic v2 was a complete rewrite in Rust, offering massive performance gains (up to 20x). It introduced new decorators like @field_validator and a new way to handle configuration. FastAPI v0.100.0+ supports both, but v2 is recommended for new projects.
Q283: How do you use dataclasses with FastAPI?
FastAPI has built-in support for standard Python dataclasses. You can use them as parameters or response models, and FastAPI will automatically convert them to/from JSON. However, Pydantic models are usually preferred for their more advanced validation features.
Q284: What is the TestClient's base_url?
The base_url allows you to set a default domain and protocol for all requests made by the client. This is useful if your application uses absolute URLs for some things.
Q285: How do you handle 405 Method Not Allowed errors?
FastAPI handles this automatically. If a route exists for a path but not for the specific HTTP method used, it returns a 405. You can customize this by adding an exception handler for HTTPException and checking for status code 405.
Q286: Explain the SessionMiddleware.
This middleware (from Starlette) provides signed cookie-based sessions. Data is stored in a cookie on the client side, and the signature ensures it hasn't been tampered with. It's a simple way to add session management without a server-side store.
Q287: How do you use BackgroundTasks with dependencies?
You can include BackgroundTasks as a parameter in your dependency function. This allows dependencies to schedule background work (like logging or cleanup) without blocking the main request processing.
6. FastAPI Intermediate Questions
Q288: Deep dive into the ASGI Specification. How does FastAPI interact with the ASGI send and receive callables?
The ASGI specification defines an asynchronous interface between a web server and a Python application. The application is an async callable that takes three arguments:
scope: A dictionary containing information about the connection (type, path, method, headers, etc.).receive: An async callable that the application uses to receive messages from the server (like request body chunks).send: An async callable that the application uses to send messages to the server (like response start and body chunks).
FastAPI (via Starlette) implements this interface. When a request arrives, FastAPI processes the scope, uses receive to get the body if needed, runs the routing and dependency logic, and then uses send to transmit the response. This low-level control is what enables WebSockets and streaming.
Q289: Explain the "C10k problem" and how ASGI/FastAPI solves it.
The C10k problem refers to the difficulty of handling 10,000 concurrent connections on a single server. Traditional WSGI servers use one thread or process per connection, which hits a limit quickly due to memory overhead and context switching. FastAPI solves this by being asynchronous. Instead of blocking a thread while waiting for a client to send data or a database to respond, the single-threaded event loop simply moves on to process other events. This allows a single process to maintain thousands of open, idle connections with very little overhead.
Q290: How would you implement a custom Dependency Injection container in FastAPI?
While FastAPI's Depends is usually sufficient, for very complex apps you might use a library like dependency-injector. You would define your providers in a container and then use a FastAPI dependency to pull the required object from the container.
# Conceptual
def get_service():
return container.my_service()
@app.get("/")
def root(service = Depends(get_service)):
return service.do_work()
Q291: What are the performance implications of using Middlewares vs Dependencies?
- Middleware: Runs for every single request. It has a slight overhead for every call. If you have many middlewares, it can add up. Middleware has less context about the specific route being called.
- Dependencies: Only run for the routes that explicitly require them. They have more context (access to path parameters, etc.). Generally, use middleware for cross-cutting concerns (logging, CORS) and dependencies for route-specific logic (auth, DB sessions). FastAPI's dependency injection is very highly optimized and has negligible overhead.
Q292: How does FastAPI handle asyncio.gather and concurrent background operations?
Since FastAPI runs in an event loop, you can use standard asyncio tools. For example, if you need to fetch data from three different external APIs, you can use asyncio.gather to start all three requests concurrently, reducing the total wait time to the duration of the slowest request.
@app.get("/concurrent")
async def concurrent_calls():
results = await asyncio.gather(call_a(), call_b(), call_c())
return results
Q293: Explain the internal mechanics of FastAPI's Routing system.
FastAPI uses a tree-based routing system (inherited from Starlette). When a request arrives, it traverses the tree of registered routes to find the first one that matches the path and method. Routes are checked in the order they were defined. This is why more specific routes (like /users/me) should be defined before more general ones (like /users/{user_id}).
Q294: How would you implement "Rate Limiting" in FastAPI without external libraries?
You can create a dependency that uses a global dictionary (or a Redis instance for distributed apps) to store request counts per IP. The dependency checks the count against the limit and the current time, raising an HTTPException(429) if the limit is exceeded.
clients = {}
def rate_limiter(request: Request):
ip = request.client.host
now = time.time()
# logic to check and update clients[ip]
Q295: Describe the process of "Database connection pooling" in an async FastAPI app.
When using an async DB driver (like asyncpg for PostgreSQL), you should create a connection pool when the application starts (in the lifespan event). Your get_db dependency then acquires a connection from the pool and yields it. This is much more efficient than opening and closing a new connection for every request.
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.pool = await asyncpg.create_pool(...)
yield
await app.state.pool.close()
Q296: How do you handle "Long Polling" and "Server-Sent Events (SSE)"?
- Long Polling: The client makes a request, and the server keeps it open until there is data to return. This is handled naturally in FastAPI by just having an
async deffunctionawaita condition. - SSE: The server keeps a persistent HTTP connection open and sends updates as they happen. You use
StreamingResponseand a generator that yields messages in the SSE format (data: my message\n\n).
Q297: Deep dive: How does Pydantic perform its validation?
Pydantic uses Python's type annotations to build a validation schema. In v2, this schema is compiled into a highly optimized Rust execution core. When data arrives, Pydantic traverses the data and the schema simultaneously, performing type checks, conversions, and running custom validators. This Rust-based core is what makes Pydantic v2 so much faster than v1.
Q298: How would you implement a "Circuit Breaker" pattern in a FastAPI service?
You can use a dependency or a wrapper around your external API calls. The circuit breaker tracks the number of failures. If they exceed a threshold, it "opens" and immediately returns an error for subsequent calls, allowing the external service time to recover. Libraries like httpx can be combined with custom logic to implement this.
Q299: Explain the security risks of CORSMiddleware and how to mitigate them.
Setting allow_origins=["*"] allows any website to make requests to your API using the user's browser credentials. This can lead to CSRF attacks. To mitigate this, you should always specify the exact list of trusted domains in allow_origins and use proper CSRF protection (like SameSite cookies or specific tokens) for sensitive operations.
Q300: How do you optimize FastAPI for "Low Latency"?
- Use
uvloop. - Use a fast JSON serializer like
orjson. - Use async database drivers and connection pooling.
- Minimize the number of middlewares.
- Use
deffor heavy blocking calls to offload them to threads. - Pre-compile Pydantic models.
- Use
root_pathcorrectly to avoid unnecessary redirects.
Q301: Describe how to implement "Multi-tenancy" at the database level in FastAPI.
- Shared Database, Shared Schema: Add a
tenant_idcolumn to every table. A dependency extracts thetenant_idfrom the request and provides it to your DB queries. - Shared Database, Separate Schema: Use a dependency to extract the tenant name and then set the search path of the DB connection to that schema.
- Separate Database: Use a dependency to extract the tenant ID and then look up the correct connection string from a central registry to provide the specific DB session.
Q302: How do you handle "Distributed Tracing" (e.g., Jaeger, Zipkin) in FastAPI?
You can use the OpenTelemetry Python SDK. It provides a middleware that automatically instruments your FastAPI application, creating spans for every request and propagating trace contexts to downstream services.
Q303: Explain how FastAPI handles "Path Operation Order".
FastAPI checks routes in the order they are added to the application. If you have two routes that could match the same URL, the one defined first wins. This is critical when mixing static paths and path parameters.
Q304: Deep dive: The Annotated type in Python and its use in FastAPI.
Annotated (Python 3.9+) allows you to attach metadata to a type hint without changing the type itself. FastAPI uses this to make dependencies and validations more readable and reusable.
from typing import Annotated
from fastapi import Depends
CurrentUser = Annotated[User, Depends(get_current_user)]
@app.get("/")
def root(user: CurrentUser): ...
Q305: How do you implement "API Documentation Versioning"?
By mounting sub-applications or using multiple APIRouter instances with different prefixes, you can have separate /v1/docs and /v2/docs pages. You can also customize the main docs page to include a version selector.
Q306: What is the "Event Loop Lag" and how do you monitor it?
Event loop lag occurs when a task blocks the loop for too long, preventing it from handling other events and increasing latency. You can monitor this using metrics libraries (like prometheus-fastapi-instrumentator) or by running a background task that periodically measures how long it takes to run a simple asyncio.sleep(0).
Q307: How do you implement "Zero-Downtime Deployment" for FastAPI?
Use a process manager like Gunicorn with Uvicorn workers. Gunicorn supports a "graceful reload" (sending a HUP signal) where it starts new worker processes and only shuts down the old ones after they have finished processing their current requests.
Q308: Explain the "N+1 Query Problem" and how it manifests in FastAPI/SQLAlchemy.
This occurs when you fetch a list of objects and then, for each object, make another query to fetch related data. In FastAPI, this often happens if your Pydantic model triggers lazy loading on a relationship. To solve this, use "Eager Loading" (like joinedload or selectinload) in your SQLAlchemy queries.
Q309: How do you use "Custom Decorators" with FastAPI path operations?
You can create a decorator that wraps your path operation function. However, you must be careful to use functools.wraps to preserve the signature and metadata, as FastAPI uses this information for its internal logic.
Q310: Describe the architecture of a "Serverless" FastAPI deployment (e.g., AWS Lambda).
You use a library like mangum to wrap your FastAPI application. Mangum converts the incoming Lambda event (from API Gateway) into the ASGI format that FastAPI understands, and then converts the FastAPI response back into the Lambda response format.
Q311: How do you handle "Global Exception Handling" for 3rd party libraries?
Create an exception handler for the base exception class of the library. FastAPI will catch any such exception raised anywhere in your code and run your handler, allowing you to return a clean, unified error response.
Q312: Explain the anyio task groups and how they relate to FastAPI.
Task groups are a way to manage multiple concurrent tasks with structured concurrency. While you don't usually use them directly in path operations, FastAPI uses them internally to manage the execution of background tasks and to ensure that all tasks are cleaned up properly when the application shuts down.
Q313: How do you implement "Health Checks" in FastAPI?
Create a simple /health endpoint that checks the status of your critical dependencies (database, cache, etc.). Use a dependency to perform these checks so you can easily reuse the logic and return a 503 if any dependency is down.
Q314: Deep dive: How does FastAPI generate the OpenAPI JSON?
FastAPI iterates through all registered routes. For each route, it inspects the function signature, the return type, the Pydantic models used in parameters, and any metadata provided in decorators. It uses Pydantic's internal schema generation to build the paths and components/schemas sections of the OpenAPI spec.
Q315: What is the "Thundering Herd" problem and how does it relate to caching in FastAPI?
This occurs when a cached item expires and multiple concurrent requests all try to regenerate it at once, overwhelming the backend. To solve this, you can use "Locked Caching" or "Stale-While-Revalidate" patterns, where only one request is allowed to update the cache while others continue to receive the old value.
Q316: How do you implement "Custom Logging" for every request and response?
The best way is to use a middleware. You capture the request details, call the next handler, capture the response details, and then log everything together. Be careful with reading the request body in middleware, as it can only be read once (you'll need to use a custom Request class to cache it).
Q317: Explain the use of Request.state.
request.state is a dictionary-like object that exists for the duration of a single request. It's used by middlewares and dependencies to store and share data (like the authenticated user or a correlation ID) without passing it through every function parameter.
Q318: How do you handle "Graceful Shutdown" of background tasks?
In the lifespan event's yield block, you should ensure that any external task queues (like Celery) are notified to stop accepting new tasks and that any in-progress local background tasks are allowed to finish or are safely cancelled.
Q319: What are "Param Alias" and why are they useful for SEO?
In Query, you can use alias to have human-readable query parameters in the URL (like search-term) while using standard variable names in your code (search_term). This is helpful for SEO-friendly URLs.
Q320: How do you implement "API Documentation Authentication"?
FastAPI allows you to pass parameters to the FastAPI constructor to configure the Swagger UI, including swagger_ui_parameters and security definitions. You can also hide the docs behind a specific path and use a dependency to require a password to access that path.
Q321: Explain the Pydantic RootModel.
RootModel (Pydantic v2) is used when your JSON data is just a primitive type (like a string or a list) at the root, rather than a dictionary. This allows you to validate and document these top-level structures easily.
Q322: How do you handle "Large File Downloads" with resume support?
You need to handle the Range header from the client and return a 206 Partial Content response with the specific byte range requested. You can use StreamingResponse to only read the required portion of the file.
Q323: What is the Uvicorn Worker Class in Gunicorn?
When running with Gunicorn, you specify worker_class="uvicorn.workers.UvicornWorker". This tells Gunicorn to use Uvicorn's ASGI implementation for its workers, combining Gunicorn's robust process management with Uvicorn's high performance.
Q324: How do you implement "Webhooks" in FastAPI?
A webhook is just another API endpoint in your application that an external service calls. You define it like any other route, but you usually want to include strong validation and signature verification to ensure the request is actually coming from the expected service. FastAPI also allows you to document the webhooks your application sends using the webhooks parameter in the FastAPI constructor.
Q325: Explain the "Double Dependency" problem and how to avoid it.
This happens when two different dependencies both need to perform the same expensive operation (like fetching a user from a DB). FastAPI avoids this by default by caching dependency results for the duration of the request. Both dependencies will receive the exact same object from the cache.
Q326: How do you use Field in Pydantic to add extra constraints?
The Field function allows you to add metadata (title, description) and constraints (min/max length, regex, numerical ranges) to model attributes. This information is used for both validation and documentation.
Q327: What is the difference between FastAPI and Starlette's Router?
FastAPI's router is a subclass of Starlette's. It adds all the "magic": dependency injection, Pydantic validation, and OpenAPI generation. You should always use FastAPI's APIRouter unless you are building something extremely low-level.
Q328: How do you handle "Deeply Nested JSON" validation?
Pydantic handles this recursively. You define models for each level of the hierarchy and use them as type hints. Pydantic will validate the entire structure in one go.
Q329: What is the anyio CapacityLimiter?
It's a way to limit the number of concurrent operations in a specific part of your code. For example, if you have an external service that can only handle 5 concurrent requests, you can use a CapacityLimiter to ensure your FastAPI app never sends more than that.
Q330: How do you implement "Custom Header Authentication"?
Use the APIKeyHeader utility from fastapi.security. It defines the header name and provides a dependency that extracts the value. You then check this value against your database of valid API keys.
Q331: Explain the Request.body() vs Request.json().
body(): Returns the raw bytes of the request body.json(): Parses the body as JSON and returns a Python dictionary. Both are async and can only be called once because the underlying stream is consumed.
Q332: How do you use Annotated with Field and Query?
This is the modern way to define parameters. It keeps the type hint clean and moves the FastAPI-specific metadata into the Annotated part.
q: Annotated[str, Query(min_length=3)] = "default"
Q333: What is the ProxyHeadersMiddleware's trusted_proxies parameter?
It's a list of IP addresses of proxies that you trust to provide accurate X-Forwarded-* headers. You should always set this to prevent IP spoofing attacks.
Q334: How do you handle "Circular Dependencies" in FastAPI Depends()?
FastAPI can't resolve circular dependencies (A depends on B, and B depends on A). You must refactor your code to break the cycle, usually by introducing a third dependency that both A and B depend on.
Q335: Explain the Lifespan state sharing.
Any data you attach to the app object during the startup phase of the lifespan event is available via request.app in your path operations. This is the recommended way to share persistent resources like DB pools or ML models.
Q336: How do you implement "Content Negotiation" (e.g., returning JSON or XML based on the Accept header)?
You can check the Accept header in your path operation and return a different Response class accordingly. You would need to use a library to convert your data to XML.
Q337: What is the "ASGI Lifecycle" message?
It's a specific type of message sent by the server to the application at startup and shutdown. FastAPI's lifespan event is the high-level abstraction over these low-level ASGI messages.
Q338: How do you handle "Idempotency" in POST requests?
You can require clients to send a unique Idempotency-Key header. Your application stores the response for each key. If a request arrives with a key that has already been processed, you return the stored response instead of running the logic again.
Q339: Explain the Pydantic computed_field.
In Pydantic v2, @computed_field allows you to include properties in the model's serialized output (JSON). This is useful for including derived values that are calculated from other fields.
Q340: How do you use FastAPI with AsyncSQLAlchemy?
You use create_async_engine and async_sessionmaker. Your get_db dependency is an async generator that yields an AsyncSession. You must await all SQLAlchemy calls (like session.execute()).
Q341: What is the anyio fail_after context manager?
It's a way to set a timeout for a block of asynchronous code. If the code takes longer than the specified time, it raises a TimeoutError. This is crucial for preventing slow external calls from hanging your API.
Q342: How do you implement "Custom OpenAPI UI" (e.g., using a different version of Swagger)?
You can disable the default docs by setting docs_url=None and then create a custom route that serves the HTML and JavaScript for your preferred UI, pointing it to your app's /openapi.json.
Q343: Explain the Starlette ExceptionMiddleware.
This is the low-level middleware that catches exceptions and runs the handlers defined in FastAPI. It ensures that even if something goes wrong, the client receives a proper HTTP response instead of the connection just dropping.
Q344: How do you handle "Request Body Streaming" for large uploads?
By using request.stream(), you can read the body in chunks as it arrives from the network. This allows you to process the data (e.g., calculating a hash or uploading to S3) without ever storing the full body in memory or on disk.
Q345: What is the Uvicorn loop parameter?
It allows you to choose which event loop implementation to use: auto, asyncio, or uvloop. uvloop is generally recommended for performance.
Q346: How do you implement "Dynamic Path Operations"?
While you usually define routes at startup, you can technically add routes to the app.router at runtime. However, this is generally discouraged as it makes the application harder to reason about and can lead to race conditions.
Q347: Explain the Pydantic AliasGenerator.
In v2, you can define an AliasGenerator in your model's config to automatically generate aliases for all fields (e.g., converting snake_case to camelCase for the API).
Q348: How do you handle "Background Task Errors"?
Background tasks are run after the response is sent, so they cannot return errors to the client. You must include your own error handling (try/except) inside the background task function and log any failures appropriately.
Q349: What is the Starlette BaseHTTPMiddleware?
It's a base class for creating custom middleware. It's easier to use than the raw ASGI interface but has some performance limitations and can cause issues with background tasks in some edge cases. The @app.middleware("http") decorator is usually preferred.
Q350: How do you implement "Pagination" in FastAPI?
The common pattern is to use skip and limit query parameters. You can create a reusable Pydantic model for the paginated response that includes the list of items and metadata like total_count.
Q351: Explain the fastapi.encoders.jsonable_encoder.
This function recursively converts any object into standard Python types (dict, list, int, etc.) that can be serialized to JSON. It's aware of Pydantic models, dataclasses, and common types like datetime and UUID.
Q352: How do you use TestClient with "Lifespan" events?
When using TestClient as a context manager (with TestClient(app) as client:), it will automatically trigger the startup and shutdown events defined in your application's lifespan.
Q353: What is the anyio sleep vs time.sleep?
time.sleep blocks the entire thread, which in an async app means blocking the whole event loop. anyio.sleep (or asyncio.sleep) is asynchronous: it tells the event loop to wake this task up after a certain time, allowing the loop to handle other requests in the meantime.
Q354: How do you handle "Database Migrations" in a FastAPI project?
The industry standard is to use Alembic. You define your models in SQLAlchemy, and Alembic generates and applies SQL migration scripts to keep your database schema in sync with your code.
Q355: Explain the Pydantic model_validator.
In v2, @model_validator(mode='after') allows you to perform validation that involves multiple fields of the model after they have been individually validated.
Q356: How do you implement "Search" functionality in FastAPI?
Usually, you take a search query as an optional query parameter. In your DB logic, you use ILIKE (in SQL) or a full-text search engine (like Elasticsearch or Postgres FTS) to find matching records.
Q357: What is the fastapi.utils.get_model_definitions?
This is an internal utility used by FastAPI to extract the JSON Schema definitions from Pydantic models to build the OpenAPI schema.
Q358: How do you handle "Rate Limiting with Redis"?
You use an async Redis client (like redis-py). In a dependency, you use the client IP as a key and the Redis INCR and EXPIRE commands to track and limit requests in a high-performance, distributed way.
Q359: Explain the Starlette GZipMiddleware internal workings.
It wraps the ASGI send callable. If the response is large enough and the client supports gzip, it intercepts the body chunks, compresses them, and updates the Content-Encoding and Content-Length headers.
Q360: How do you use FastAPI with GraphQL?
You can use a library like strawberry-graphql. You define your schema using Strawberry and then mount the Strawberry FastAPI integration as a route in your application.
Q361: What is the Uvicorn httptools vs h11?
httptools is faster (Rust/C) but h11 is pure Python and easier to install. Uvicorn uses httptools if available, falling back to h11.
Q362: How do you implement "Feature Flags" in FastAPI?
You can use a dependency that checks a configuration file, an environment variable, or an external service (like LaunchDarkly) to determine if a specific feature is enabled, and then adjusts the route logic or availability accordingly.
Q363: Explain the Pydantic TypeAdapter.
In v2, TypeAdapter allows you to validate and serialize data against any type (not just a BaseModel), which is very useful for validating lists of primitives or complex types.
Q364: How do you handle "Websocket Authentication"?
Since WebSockets are established via an initial HTTP request, you can perform authentication during that handshake (e.g., checking a query parameter or a cookie). FastAPI allows you to use dependencies in your websocket endpoint to handle this.
Q365: What is the Starlette StaticFiles html parameter?
If set to True, it will look for an index.html file when a directory is requested, allowing you to easily serve a single-page application (SPA).
Q366: How do you implement "Soft Deletes" in FastAPI?
Add a deleted_at timestamp column to your database tables. In your FastAPI logic, you filter your queries to only return records where deleted_at is null.
Q367: Explain the fastapi.params.Depends object.
It's a class that stores the dependency function and the use_cache flag. When FastAPI encounters it in a function signature, it triggers its internal dependency resolution logic.
Q368: How do you handle "Database Deadlocks" in an async environment?
Deadlocks are handled the same way as in sync environments (using transactions and retry logic). However, because you are in an async loop, you must be careful not to block the loop while retrying.
Q369: What is the Uvicorn log_config parameter?
It allows you to provide a standard Python logging configuration dictionary to fully customize how Uvicorn logs messages (format, levels, handlers).
Q370: How do you implement "Custom OpenAPI Tags"?
You can pass a openapi_tags list to the FastAPI constructor. This allows you to add descriptions and external documentation links to the tags shown in the Swagger UI.
Q371: Explain the Pydantic validate_call.
In v2, @validate_call allows you to apply Pydantic validation to any Python function, not just FastAPI path operations.
Q372: How do you handle "Multiple Query Parameters with the same name"?
Define the type as List[str]. FastAPI will automatically collect all values from the query string into that list.
Q373: What is the Starlette Response background parameter?
It's a low-level way to attach a BackgroundTask directly to a response object. FastAPI's BackgroundTasks dependency is just a higher-level way to use this feature.
Q374: How do you implement "Role-Based Access Control (RBAC)"?
Create a dependency that takes the required roles as arguments. It then checks the roles of the authenticated user (from another dependency) and raises a 403 Forbidden if the user doesn't have the necessary permissions.
Q375: Explain the Uvicorn reload_dirs parameter.
It allows you to specify which directories Uvicorn should watch for changes when running with --reload. This is helpful for ignoring large data directories or virtual environments.
Q376: How do you handle "Binary Data" in request bodies?
You can use the Request.body() method to get the raw bytes, or define a parameter as bytes with Body(...).
Q377: What is the fastapi.security.utils.get_authorization_scheme_param?
It's a utility that parses the Authorization header and splits it into the scheme (e.g., Bearer) and the actual parameter (the token).
Q378: How do you implement "Request ID" tracking?
Use a middleware to generate a unique UUID for every request. Store it in request.state and include it in your logs and as a custom header in the response (X-Request-ID).
Q379: Explain the Pydantic model_json_schema.
In v2, this method returns the JSON Schema representation of the model. It's the core of how FastAPI generates the OpenAPI definitions.
Q380: How do you handle "Timeout" for individual requests?
You can use anyio.fail_after inside your path operation or dependency. If the logic takes too long, it will raise an error that you can catch and return a 504 Gateway Timeout.
Q381: What is the Starlette TestClient follow_redirects parameter?
It determines if the client should automatically follow HTTP redirects (like 301 or 302). It's useful for testing redirection logic.
Q382: How do you implement "Audit Logging"?
Use a middleware or a background task to record every write operation (POST, PUT, DELETE) to a separate audit log table, including the user, the time, the resource, and the changes made.
Q383: Explain the Uvicorn limit_concurrency parameter.
It sets a maximum number of concurrent connections that Uvicorn will handle. This is a simple way to protect your server from being overwhelmed.
Q384: How do you handle "Large JSON responses" without blocking?
If your response is massive, converting it to a string can be expensive. You can use a StreamingResponse to serialize and send it in chunks, or use ORJSONResponse for maximum performance.
Q385: How do you handle "Environment-specific OpenAPI documentation"?
You can check an environment variable (like ENV) and set docs_url=None and redoc_url=None in your FastAPI constructor if the environment is production, ensuring your API schema isn't publicly exposed.
Q386: What is the purpose of APIRouter.callback?
This allows you to define endpoints that your API will call in response to certain events (webhooks that your app triggers). This information is included in the generated OpenAPI documentation, making it easier for clients to know what webhooks they can expect to receive from your service.
Q387: Explain the difference between FastAPI(swagger_ui_oauth2_redirect_url="/oauth2-redirect") and other parameters.
This parameter specifies the URL that the Swagger UI uses to handle OAuth2 authentication redirects. By default, it uses a hosted script from the CDN, but you can override it if you want to host the redirect handler locally for security or compliance reasons.
Q388: How do you use pydantic.computed_field for complex API responses?
computed_field (available in Pydantic v2) allows you to define a method that acts as a field in the serialized JSON output. This is perfect for calculating fields on the fly (like a total price or a full name) without storing them in the database or modifying the internal model structure.
from pydantic import BaseModel, computed_field
class Invoice(BaseModel):
items_total: float
tax_rate: float
@computed_field
def total_price(self) -> float:
return self.items_total * (1 + self.tax_rate)
Q389: Describe the anyio AsyncFile interface.
AsyncFile provides an asynchronous wrapper around standard file operations. This allows you to read from or write to the filesystem without blocking the main event loop. FastAPI uses this internally for things like UploadFile.
Q390: How do you implement "API Key Rotation" support?
You can create a dependency that checks a list of valid API keys for a user. If a key is marked as "retiring", the dependency still allows the request but can add a custom header to the response (X-API-Key-Status: Deprecated) to warn the client to switch to a newer key.
Q391: Explain the mechanics of Starlette SessionMiddleware's max_age.
The max_age parameter defines the expiration time (in seconds) for the session cookie. Once this time passes, the browser will automatically delete the cookie. However, for true security, you should also include a timestamp inside the signed session data and verify it on the server to prevent replay attacks with old cookies.
Q392: How do you handle "Optional Request Bodies"?
By setting the default value of the Pydantic model parameter to None, you make the entire body optional. You must then handle the case where the parameter is None in your function logic.
@app.post("/items/")
async def create_item(item: Item | None = None):
if item is None:
return {"msg": "No body provided"}
return item
Q393: What is the Starlette Response.render method?
This is the internal method that converts the Python data (like a dictionary) into raw bytes that can be sent over the wire. Custom response classes override this method to implement different serialization formats (like XML or binary protocols).
Q394: How do you use TestClient with "Lifespan" events and mock?
When using TestClient in a with block, you can use standard Python unittest.mock to patch global objects before the lifespan startup logic runs. This allows you to mock things like database engine creation or external service clients that are initialized at startup.
Q395: Explain the Uvicorn proxy_headers security implications.
While proxy_headers is necessary behind Nginx, it makes the app vulnerable to spoofing if it's exposed directly to the internet. An attacker can send a fake X-Forwarded-For header to bypass IP-based rate limiting or authentication. Always ensure your app only accepts these headers from trusted proxy IPs.
Q396: How do you implement "Data Masking" for sensitive response fields?
The best way is to use Pydantic models. You define a "Public" version of your model that doesn't include the sensitive fields, and set it as the response_model in your path operation. FastAPI will automatically filter out any extra data returned from your database.
Q397: What is the fastapi.dependencies.utils.get_dependant function?
This is an internal FastAPI function that parses a function signature and builds a "Dependant" object. This object contains all the information needed to resolve dependencies and validate parameters at runtime.
Q398: Describe how to handle "Websocket Disconnections" gracefully.
You should wrap your websocket communication loop in a try...except block that catches WebSocketDisconnect. This allows you to perform cleanup (like removing the user from a "room" list) when the client closes the connection or loses their network.
from fastapi import WebSocketDisconnect
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
try:
while True:
await websocket.receive_text()
except WebSocketDisconnect:
# Cleanup logic here
pass
Q399: How do you use Field(exclude=True) in Pydantic?
Setting exclude=True tells Pydantic to ignore this field when converting the model to a dictionary or JSON. This is a simple way to keep internal state in a model without ever exposing it in the API response.
Q400: Explain the concept of "ASGI Middleware" vs "HTTP Middleware".
- ASGI Middleware: Operates at the lowest level, dealing with raw ASGI messages (scope, receive, send). It's very powerful but complex to write.
- HTTP Middleware: (FastAPI's
@app.middleware("http")) operates at a higher level, giving you aRequestobject and expecting aResponseobject. It's much easier to use for standard web tasks.
Q401: How do you implement "Content-Type" restricted endpoints?
You can create a dependency that inspects the Content-Type header and raises a 415 Unsupported Media Type error if it doesn't match your requirements (e.g., forcing a specific endpoint to only accept text/csv).
Q402: What is the Uvicorn timeout_keep_alive parameter?
It defines how long (in seconds) the server should keep a persistent connection open while waiting for the next request from the same client. Tuning this can improve performance for high-traffic sites but consumes more memory for open sockets.
Q403: How do you handle "Complex Nested Query Parameters"?
Standard query parameters are flat. To handle complex structures, you can take a single query parameter as a JSON string and use a Pydantic model to validate it, or use a custom dependency that manually parses multiple parameters into a structured object.
Q404: Explain the use of APIRouter.on_event.
Similar to the main FastAPI object, a router can have its own startup and shutdown events. This is useful for initializing and cleaning up resources that are specific to a single module of your application. (Note: standard practice is moving towards lifespan).
Q405: How do you implement "Request Logging with Correlation IDs"?
- A middleware checks for an
X-Correlation-IDheader; if missing, it generates one. - The middleware stores this ID in a
ContextVar(to ensure it's available throughout the async request task). - Your logging configuration is updated to include the value from that
ContextVarin every log message, allowing you to trace a single request across multiple services.
Q406: What is the Pydantic Discriminator field?
It's used with Union types to tell Pydantic exactly which model to use for validation based on a specific field value (e.g., a "type" field). This makes handling polymorphic data structures much faster and more reliable.
from typing import Union, Literal
from pydantic import BaseModel, Field
class Cat(BaseModel):
type: Literal["cat"]
meows: bool
class Dog(BaseModel):
type: Literal["dog"]
barks: bool
class Pet(BaseModel):
item: Union[Cat, Dog] = Field(..., discriminator="type")
Q407: Describe how to use FastAPI with Trio.
While Uvicorn primarily supports asyncio, you can run FastAPI on top of Trio using the Hypercorn server. This is useful if you prefer Trio's model of structured concurrency.
Q408: How do you handle "Large Multipart/Form-Data" bodies?
Multipart bodies are parsed chunk by chunk. If you use UploadFile, the individual parts are written to temporary files as they arrive, preventing memory exhaustion even with multiple large file uploads.
Q409: Explain the Starlette RedirectResponse internal status codes.
By default, RedirectResponse uses 307 Temporary Redirect for temporary moves and 308 Permanent Redirect for permanent ones. These are preferred over 302 and 301 because they preserve the original HTTP method (e.g., a POST remains a POST after redirect).
Q410: How do you implement "Custom Header-based Routing"?
FastAPI doesn't support this natively in the router. However, you can create a single entry-point route that takes a header as a dependency and then internally dispatches the request to different logic functions based on that header value.
Q411: What is the Uvicorn limit_max_requests parameter?
It tells a worker process to restart after handling a certain number of requests. This is a common strategy for mitigating slow memory leaks in production environments.
Q412: How do you handle "JSON Schema Customization" for Pydantic models?
You can use the json_schema_extra config option to add custom properties to the generated JSON Schema (like x-internal-id). These properties will then appear in your OpenAPI definition.
Q413: Describe the Starlette BackgroundTasks vs a Task Queue (like Celery).
BackgroundTasks: Runs in the same process, good for light tasks (sending an email). If the server crashes, the task is lost.Celery: Runs in a separate process/server, good for heavy tasks (image processing). It uses a broker (like Redis) for persistence and retry support.
Q414: How do you use TestClient to test "CORS" headers?
You make a request using the OPTIONS method and include headers like Origin and Access-Control-Request-Method. You then verify that the response includes the expected Access-Control-Allow-Origin and other CORS-related headers.
Q415: Explain the fastapi.openapi.utils.get_openapi function.
This is the function that actually crawls your application, collects all the metadata from routes, parameters, and models, and assembles the final dictionary that follows the OpenAPI specification.
Q416: How do you implement "Response Transformation" using middleware?
In your middleware, after calling call_next(request), you can get the response.body(). You then modify this body (e.g., wrapping every JSON response in a standard metadata object) and return a new Response object with the modified content.
Q417: What is the Pydantic model_post_init?
It's a hook that runs after a model has been initialized and validated. You can use it to perform additional setup or calculations that depend on the validated data but don't need to be part of the validation logic itself.
Q418: Describe how to handle "Rate Limiting with Burst support".
Instead of a simple counter, you use the "Token Bucket" algorithm. A bucket holds a maximum number of tokens (burst). Each request consumes a token. Tokens are added back to the bucket at a fixed rate. This allows clients to make occasional bursts of requests while keeping the long-term average under control.
Q419: How do you use FastAPI with Prometheus for monitoring?
The prometheus-fastapi-instrumentator library provides a middleware that automatically records metrics for every request (path, status code, latency). It also provides a /metrics endpoint for Prometheus to scrape.
Q420: Explain the Starlette Response.set_cookie samesite parameter.
This parameter is crucial for security. samesite="lax" or "strict" prevents the cookie from being sent in cross-site requests, which is the primary defense against CSRF attacks.
Q421: How do you implement "Global Dependency Overrides" in the main app?
You don't override them globally; instead, you use the app.dependency_overrides dictionary. This is specifically designed for testing and allows you to replace any dependency function anywhere in your app with a mock version.
Q422: What is the Uvicorn backlog parameter?
It's the maximum number of queued connections that the operating system will hold before it starts refusing new ones. Increasing this can help handle sudden spikes in traffic.
Q423: How do you handle "Slow Client Attacks" (e.g., Slowloris)?
ASGI servers like Uvicorn have built-in timeouts for reading headers and bodies. You can tune these using parameters like timeout_keep_alive. Additionally, running FastAPI behind a robust reverse proxy like Nginx provides another layer of protection.
Q424: Describe the Pydantic BeforeValidator and AfterValidator.
In v2, these allow you to run custom validation logic either before Pydantic does its own checks (e.g., to coerce a string into a specific format) or after (e.g., to perform extra checks on a validated object).
Q425: How do you implement "Static API Documentation" generation?
You can write a small script that imports your app object and calls app.openapi(). You then save the resulting dictionary as a JSON or YAML file, which can be used to generate static HTML documentation with tools like swagger-cli.
Q426: Explain the Starlette WebSocket.send_json method.
It's a convenience method that takes a Python object, converts it to a JSON string using the standard json module, and sends it as a text message over the WebSocket connection.
Q427: How do you use FastAPI with SQLModel?
SQLModel is a library that combines Pydantic models and SQLAlchemy models into a single class. This eliminates code duplication and ensures that your database models and API models are always in sync. FastAPI has native support for SQLModel.
Q428: Describe how to handle "Nested URL Prefixes" with APIRouter.
You can include a router inside another router. Each router can have its own prefix. FastAPI will concatenate these prefixes, allowing you to create complex, hierarchical URL structures (e.g., /api/v1/users/admin/settings).
Q429: How do you implement "Custom Status Code logic" based on response data?
Since you define the status code in the decorator, you can't change it easily based on the return value. To do this, you must either raise an HTTPException or return a Response object where you manually set the status_code.
Q430: What is the Uvicorn fd parameter?
It stands for "File Descriptor". It allows you to bind Uvicorn to an already open socket passed by a process manager (like systemd or circus). This is a robust way to manage long-running server processes.
Q431: How do you handle "Large JSON request bodies" without blocking the thread?
Pydantic's validation is CPU-intensive. If the JSON is huge, it can block the event loop. In such cases, you can run the validation in a separate thread using anyio.to_thread.run_sync, keeping the main loop responsive for other clients.
Q432: Explain the Pydantic AliasChoices.
In v2, AliasChoices allows a field to be populated from multiple different names in the input data. This is useful for handling legacy APIs or cases where different clients use different naming conventions.
Q433: How do you implement "Request Caching" at the FastAPI level?
You can use a library like fastapi-cache2. It provides a decorator that automatically caches the response of a path operation (usually in Redis) based on the input parameters, drastically reducing database load for expensive queries.
Q434: Describe the Starlette Response headers property.
It's a mutable dictionary-like object representing the HTTP headers that will be sent in the response. You can add custom headers here, but remember that some headers (like Content-Length) are managed automatically by the framework.
Q435: How do you use FastAPI with Keycloak for authentication?
You use the OAuth2AuthorizationCodeBearer class to define the Keycloak authorization and token endpoints. Your frontend gets a token from Keycloak, sends it to FastAPI, and a dependency validates the token (signature and claims) against Keycloak's public keys.
Q436: Explain the Uvicorn ssl_keyfile and ssl_certfile parameters.
These are used to configure SSL/TLS directly in Uvicorn, allowing your app to serve HTTPS traffic. However, in production, it's usually better to handle SSL at the reverse proxy level (Nginx/Traefik) or using a load balancer.
Q437: How do you handle "Recursive Dependency Resolution"?
FastAPI uses a depth-first search to build a graph of all dependencies. It handles cases where multiple branches of the graph share the same dependency by caching the result, but it will error if it detects a cycle.
Q438: Describe the Pydantic TypeAdapter.get_json_schema method.
This method allows you to generate a JSON Schema for any Python type, even if it's not a BaseModel. This is what FastAPI uses to document things like List[str] in the OpenAPI spec.
Q439: How do you implement "Conditional Responses" (e.g., using If-None-Match and ETag)?
You calculate a hash (ETag) of your response data. If the client sends an If-None-Match header with that same hash, you return a 304 Not Modified response without a body, saving bandwidth and processing time.
Q440: Explain the Starlette StreamingResponse chunk_size implications.
The chunk_size is not a parameter of the response itself, but rather a detail of how your generator yields data. Small chunks mean lower latency but higher overhead; large chunks are more efficient for throughput but can delay the start of the transmission.
Q441: How do you use FastAPI with Sentry for error tracking?
The Sentry Python SDK includes a FastAPI integration. You initialize it at the start of your app, and it automatically captures every unhandled exception, including full request details and context, making it easy to debug production issues.
Q442: Describe how to handle "Optional Fields with Defaults" in Pydantic models.
If a field has a default value, it is not required in the input JSON. If the input JSON does include it, Pydantic uses the provided value. If the input omits it, Pydantic uses the default. You can also use Field(default_factory=...) for dynamic defaults like timestamps.
Q443: How do you implement "Global Response Wrapping"?
Use a middleware. After the path operation runs and returns a Response, you can read its content, wrap it in your standard JSON envelope (e.g., adding success, data, and error keys), and return a new JSONResponse with the wrapped data.
Q444: Explain the Uvicorn http parameter.
It allows you to force a specific HTTP implementation: auto, h11, or httptools. This is mainly used for debugging or working around specific compatibility issues.
Q445: How do you handle "Streaming Uploads to S3"?
Inside your path operation, use request.stream() to get chunks of the file. Use an async S3 client (like aioboto3) to start a multipart upload, sending each chunk to S3 as soon as you receive it from the network.
Q446: Describe the Pydantic BaseModel.model_dump method.
In v2, model_dump replaces the old dict() method. It converts the model instance into a Python dictionary. You can use the include and exclude parameters to control exactly which fields are included in the output.
Q447: How do you implement "Graceful API Deprecation"?
- Add a
deprecated=Trueparameter to the path operation decorator (this marks it in Swagger). - Add a
Warningheader to the response (Warning: 299 - "This endpoint is deprecated"). - Update your documentation to point users to the new version.
Q448: Explain the Starlette WebSocket.receive_json method.
It receives a text message over the WebSocket, and then uses the standard json.loads function to convert it into a Python object (dictionary or list). If the message is not valid JSON, it will raise an error.
Q449: How do you use FastAPI with Elasticsearch?
Use the official elasticsearch-py async client. Create the client in the lifespan event and use a dependency to provide it to your path operations. You can use Pydantic models to validate the data you send to and receive from Elasticsearch.
Q450: Describe how to handle "Complex Validation logic across multiple models".
You can use a dependency that takes multiple models as parameters. The dependency can then perform complex cross-validation logic (e.g., checking that a start date in one model is before an end date in another) and raise an HTTPException if it fails.
Q451: How do you implement "Dynamic OpenAPI URL"?
In the FastAPI constructor, you can set openapi_url to a dynamic string based on environment variables or other configuration. This allows you to hide the schema file or serve it from a different path.
Q452: Explain the Uvicorn interface parameter.
It allows you to specify whether the application follows the asgi2 or asgi3 specification. FastAPI is an asgi3 framework, which is the current standard.
Q453: How do you handle "Client Side Caching" with Cache-Control headers?
In your path operation, you can set the Cache-Control header on the Response object (e.g., response.headers["Cache-Control"] = "max-age=3600"). This tells the client's browser (and any intermediate proxies) to cache the response for one hour.
Q454: Describe the Pydantic Serialization vs Validation.
- Validation: Checking incoming data against the model schema (input).
- Serialization: Converting a model instance back into a JSON-compatible format (output).
Pydantic v2 allows you to customize both independently using decorators like
@field_validatorand@field_serializer.
Q455: How do you implement "Batch Request Processing"?
The best way is to define a path operation that takes a List of models as its body. Your application then iterates through the list, performs the required logic for each item (potentially using asyncio.gather for speed), and returns a list of results.
Q456: Explain the Starlette Response delete_cookie method.
This method adds a Set-Cookie header to the response with an expiration date in the past. This tells the client's browser to immediately delete the specified cookie.
Q457: How do you use FastAPI with Kafka?
Use an async Kafka library like aiokafka. Initialize the producer/consumer in the lifespan event. You can use a background task to send messages to Kafka so that you don't block the API response.
Q458: Describe how to handle "File format conversion" (e.g., HTML to PDF) in FastAPI.
Since conversion is usually CPU-intensive, you should either:
- Run the conversion in a separate thread using
anyio.to_thread.run_sync. - Offload the task to a worker queue like Celery and return a "task ID" to the client.
Q459: How do you implement "Custom Header-based Authentication" with Security?
Use the APIKeyHeader class. You can then use the Security() function in your parameters to require this header and optionally define scopes that are required to access the endpoint.
Q460: Explain the Uvicorn ws parameter.
It allows you to choose the WebSocket implementation: auto, none, websockets, or wsproto. websockets is the recommended high-performance implementation.
Q461: How do you handle "Database Session leak" detection?
You can use a middleware that checks if any database sessions are still open after a request has finished. In SQLAlchemy, you can also use events to track when sessions are created and closed and log any that aren't closed within a reasonable timeout.
Q462: Describe the Pydantic ValidationAlias.
In v2, validation_alias allows you to specify a different name for a field during validation (input) than during serialization (output). This is helpful when an external API sends you data with weird keys that you want to rename in your code.
Q463: How do you implement "Health check dependencies"?
Create a dependency that performs a light-weight check on a resource (e.g., running SELECT 1 on a DB). You then use this dependency in your /health endpoint. This ensures that the health check logic is decoupled from the route itself.
Q464: Explain the Starlette BackgroundTasks add_task signature.
It takes a callable (the function to run) followed by any number of arguments and keyword arguments that should be passed to that function when it is executed.
Q465: How do you use FastAPI with Redis Streams?
Use the XADD and XREAD commands from an async Redis client. You can have a long-running background task (started in lifespan) that reads from a stream and processes events as they arrive, potentially using WebSockets to notify connected clients.
Q466: Describe how to handle "Complex Regex validation" in path parameters.
If a regex is too complex to fit in a Path() parameter, you can take the parameter as a raw str and then use a dependency to perform the regex check and raise an HTTPException if it doesn't match.
Q467: How do you implement "Response filtering" based on user roles?
Use a response_model that includes all possible fields. In your path operation, you manually check the user's role and set unauthorized fields to None. Alternatively, use different Pydantic models for different roles and select the correct one at runtime.
Q468: Explain the Uvicorn access_log parameter.
It's a boolean flag that determines whether Uvicorn should log every incoming request to the console. In production, you might want to disable this if you are already logging requests in your own middleware.
Q469: How do you handle "Concurrent Request limits" per user?
Use a Redis-based semaphore. In a dependency, you try to acquire a lock for the user. If the user already has the maximum allowed number of concurrent requests, you raise a 429 Too Many Requests error.
Q470: Describe the Pydantic Generic models.
Generic models allow you to define a model where the type of one or more fields is a placeholder. This is extremely useful for creating reusable structures like Page[T] for pagination, where T is the type of the items on the page.
from typing import TypeVar, Generic
from pydantic import BaseModel
T = TypeVar("T")
class Page(BaseModel, Generic[T]):
items: list[T]
total: int
Q471: How do you implement "API Signature Verification"?
Use a middleware or dependency that takes the raw request body and a signature header. It calculates the HMAC-SHA256 hash of the body using a shared secret and compares it to the provided signature to ensure the request hasn't been tampered with.
Q472: Explain the Starlette Response media_type parameter.
It defines the Content-Type header of the response. FastAPI uses this to determine how to encode the data (e.g., using json.dumps for application/json).
Q473: How do you use FastAPI with MongoDB?
Use an async driver like Motor. Initialize the client in lifespan and use a dependency to provide the database object. You can use Pydantic models with custom ObjectId support to validate your MongoDB documents.
Q474: Describe how to handle "Distributed Locking" in FastAPI.
Use Redis or ZooKeeper. You create a dependency that acquires a lock for a specific resource ID. This ensures that only one worker across your entire cluster can process a specific task or resource at a time.
Q475: How do you implement "Custom Swagger UI themes"?
FastAPI allows you to provide a swagger_ui_parameters dictionary to the FastAPI constructor. You can use this to inject custom CSS or change the layout of the Swagger UI.
Q476: Explain the Uvicorn root_path vs Nginx proxy_pass.
Nginx handles the actual URL rewriting, while root_path tells FastAPI what the rewrite was, so it can generate correct absolute URLs in the OpenAPI schema and handle redirects correctly.
Q477: How do you handle "Large Binary file uploads" with processing?
Use UploadFile. As chunks of the file arrive, you can read them from the file object and process them (e.g., calculating a checksum) without waiting for the entire file to be uploaded.
Q478: Describe the Pydantic Config.extra = 'allow'.
This setting allows you to create model instances that contain extra fields not defined in the schema. These extra fields will be preserved and included in the output, which is useful for working with highly dynamic or unpredictable data.
Q479: How do you implement "Request-specific timeouts" for DB queries?
Most async DB drivers allow you to pass a timeout argument to their execution methods. You can use a dependency to set a default timeout based on the route or even allow clients to specify a timeout via a header.
Q480: Explain the Starlette Response status_code property.
It's a mutable integer representing the HTTP status code. You can change this property at any time before the response is sent to the client.
Q481: How do you use FastAPI with GRPC?
You typically run a separate GRPC server and use a GRPC client inside your FastAPI path operations to communicate with it. This allows you to expose a standard REST API to the public while using high-performance GRPC internally.
Q482: Describe how to handle "Complex Data Migrations" during startup.
Don't do complex migrations in the lifespan startup event, as it will delay the start of your server and can lead to timeouts. Instead, use a separate migration tool (like Alembic) and run it as part of your deployment pipeline.
Q483: How do you implement "Client-side ETag verification" in middleware?
The middleware calculates the hash of the response body. If the client's If-None-Match header matches, the middleware replaces the response with a 304 Not Modified and an empty body before it's sent to the wire.
Q484: Explain the Uvicorn log_level parameter.
It sets the minimum severity level of messages that Uvicorn will log (e.g., info, warning, error). Setting it to error in production can reduce log noise and improve performance.
Q485: How do you handle "Custom OpenAPI operation IDs"?
By default, FastAPI generates operation IDs based on your function names. You can override this by providing an operation_id parameter to the path operation decorator, which is helpful for generating cleaner client SDKs.
7. FastAPI Advanced Questions
Q486: What is Python and what makes it popular?
Python is a high-level, interpreted, general-purpose language known for readable syntax, a large standard library, and a huge ecosystem. It is popular for web development, automation, data science, scripting, and backend systems.
name = "Python"
print(f"Hello, {name}")
Q487: What is the difference between = and == in Python?
= assigns a value to a variable. == compares two values for equality.
x = 10
print(x == 10) # True
Q488: What are Python's main built-in data types?
Common built-ins include int, float, bool, str, list, tuple, set, dict, and None.
data = {
"name": "Alice",
"age": 30,
"tags": ["python", "backend"],
}
Q489: What is the difference between mutable and immutable types?
Mutable objects can change in place, while immutable objects cannot. Lists and dicts are mutable; strings, tuples, and ints are immutable.
items = [1, 2]
items.append(3)
text = "hi"
text = text + "!"
Q490: What is truthiness in Python?
Python treats some values as false in boolean contexts, including None, 0, 0.0, "", [], {}, and set(). Everything else is usually truthy.
if []:
print("won't run")
Q491: What is the difference between is and ==?
== checks value equality. is checks object identity, meaning whether two names point to the same object.
a = [1, 2]
b = [1, 2]
print(a == b) # True
print(a is b) # False
Q492: How do if, elif, and else work?
They control branching based on conditions. Python executes the first matching branch.
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "C"
Q493: How do for and while loops differ?
for iterates over an iterable. while repeats until a condition becomes false.
for n in range(3):
print(n)
i = 0
while i < 3:
print(i)
i += 1
Q494: What do break, continue, and pass do?
break exits a loop, continue skips to the next iteration, and pass is a no-op placeholder.
for n in range(5):
if n == 2:
continue
if n == 4:
break
print(n)
Q495: What are list, set, and dict comprehensions?
They are compact ways to build collections.
squares = [x * x for x in range(5)]
unique = {x for x in [1, 1, 2, 3]}
mapping = {x: x * 2 for x in range(3)}
Q496: What is a function in Python?
A function is a reusable block of code that can take arguments and return a value.
def add(a, b):
return a + b
Q497: What is the difference between return and printing?
return sends a value back to the caller. print only displays output and returns None.
def f():
print("x")
def g():
return "x"
Q498: What are default arguments and what is the common pitfall?
Default arguments are evaluated once at function definition time. Using a mutable default like [] can cause shared state across calls.
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
Q499: What are *args and **kwargs?
*args collects extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dict.
def demo(*args, **kwargs):
return args, kwargs
Q500: What is variable scope in Python?
Python uses LEGB scope resolution: Local, Enclosing, Global, Built-in.
x = 1
def outer():
y = 2
def inner():
return x + y
return inner()
Q501: What do global and nonlocal do?
global lets a function assign to a module-level name. nonlocal lets an inner function rebind a variable from an enclosing function.
count = 0
def inc():
global count
count += 1
Q502: How do exceptions work in Python?
Exceptions signal runtime errors. Use try, except, else, and finally to handle them cleanly.
try:
value = int("abc")
except ValueError:
value = 0
finally:
print("done")
Q503: Why use raise and custom exceptions?
raise lets you signal specific failures. Custom exceptions make error handling clearer.
class InvalidAgeError(Exception):
pass
def set_age(age):
if age < 0:
raise InvalidAgeError("age must be positive")
Q504: What is the difference between import module and from module import name?
import module keeps the namespace explicit. from module import name imports specific objects directly.
import math
from math import sqrt
Q505: What is a module and what is a package?
A module is a single Python file. A package is a directory of modules, usually with an __init__.py file.
# package/
# __init__.py
# utils.py
10. Python Core Language — Fundamentals & Advanced
Q506: What is Python's data model and why does it matter?
Python's data model defines how objects behave with built-in operations. By implementing "dunder" (double-underscore) methods, any class can integrate with Python syntax like len(), [], iteration, arithmetic, and comparison.
class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):
return f"Vector({self.x}, {self.y})"
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __len__(self):
return 2
v = Vector(1, 2) + Vector(3, 4)
print(repr(v)) # Vector(4, 6)
print(len(v)) # 2
Q507: What is the difference between __repr__ and __str__?
__repr__ returns an unambiguous developer-facing representation, ideally one that can recreate the object. __str__ returns a human-readable string used by print() and str(). If only __repr__ is defined, it acts as a fallback for __str__ as well.
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):
return f"Point({self.x!r}, {self.y!r})"
def __str__(self):
return f"({self.x}, {self.y})"
p = Point(1, 2)
print(repr(p)) # Point(1, 2) — used in debuggers, logs
print(str(p)) # (1, 2) — used in print()
Q508: How do __eq__ and __hash__ interact?
If you define __eq__, Python sets __hash__ to None unless you also define it — making the object unhashable. Objects used as dict keys or set members must be hashable. When __eq__ is defined, __hash__ must be defined consistently so that equal objects have the same hash.
class Card:
def __init__(self, rank, suit):
self.rank, self.suit = rank, suit
def __eq__(self, other):
return self.rank == other.rank and self.suit == other.suit
def __hash__(self):
return hash((self.rank, self.suit))
cards = {Card("A", "spades"), Card("A", "spades")}
print(len(cards)) # 1 — deduplication works correctly
Q509: What are mutable vs immutable types in Python?
Immutable objects (int, float, str, tuple, frozenset, bytes) cannot be changed after creation. Mutable objects (list, dict, set, bytearray) can. Immutability enables hashing and safe sharing between threads.
# Immutable — reassignment creates a new object
a = "hello"
b = a
a += " world"
print(b) # "hello" — b is unaffected
# Mutable — shared reference changes both names
x = [1, 2, 3]
y = x
x.append(4)
print(y) # [1, 2, 3, 4] — y sees the change
Q510: What is string/integer interning in Python?
CPython caches small integers (typically -5 to 256) and compile-time string literals, returning the same object for identical values. This is an implementation detail, not part of the language spec. Rely on == for value equality, not is.
a = 256
b = 256
print(a is b) # True — interned
c = 257
d = 257
print(c is d) # False — may not be interned (implementation-dependent)
s1 = "hello"
s2 = "hello"
print(s1 is s2) # True — string literal interned at compile time
Q511: How do list comprehensions differ from generator expressions?
List comprehensions evaluate eagerly and build the entire list in memory. Generator expressions are lazy — they produce one item at a time and use O(1) memory. Use generators when you only need to iterate once or when the dataset is large.
# List comprehension — builds list immediately
squares_list = [x * x for x in range(10)]
# Generator expression — lazy, memory-efficient
squares_gen = (x * x for x in range(10))
# Only materialize when needed
print(sum(squares_gen)) # 285
Q512: How do *args and **kwargs work internally?
*args collects extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dict. They follow a strict parameter order: positional, *args, keyword-only, **kwargs.
def demo(a, b, *args, key="default", **kwargs):
print(a, b) # positional
print(args) # extra positionals as tuple
print(key) # keyword-only
print(kwargs) # extra keywords as dict
demo(1, 2, 3, 4, key="custom", x=10, y=20)
# 1 2
# (3, 4)
# custom
# {'x': 10, 'y': 20}
Q513: What is a closure and how does it capture variables?
A closure is a nested function that captures variables from its enclosing scope. Python captures variables by reference, not by value — a common pitfall in loops. The nonlocal keyword lets an inner function rebind (not just read) an enclosing variable.
def make_counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
c = make_counter()
print(c()) # 1
print(c()) # 2
# Loop closure pitfall
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs]) # [2, 2, 2] — all capture the same i
# Fix: use default argument to capture by value
funcs = [lambda i=i: i for i in range(3)]
print([f() for f in funcs]) # [0, 1, 2]
Q514: How do decorators work, and what does functools.wraps do?
A decorator is a callable that takes a function and returns a replacement. Without functools.wraps, the wrapper loses the original function's __name__, __doc__, and other metadata. Always use @functools.wraps(func) to preserve them.
import functools
def timer(func):
@functools.wraps(func) # preserves __name__, __doc__, etc.
def wrapper(*args, **kwargs):
import time
start = time.perf_counter()
result = func(*args, **kwargs)
print(f"{func.__name__} took {time.perf_counter() - start:.4f}s")
return result
return wrapper
@timer
def slow():
"""Does something slow."""
import time; time.sleep(0.1)
slow()
print(slow.__name__) # "slow" — not "wrapper"
print(slow.__doc__) # "Does something slow."
Q515: How do stacked decorators and class decorators work?
Stacked decorators apply bottom-up. Class decorators receive the class object itself and return a replacement — useful for registering classes or adding class-level behavior.
import functools
def bold(func):
@functools.wraps(func)
def wrapper(*a, **kw):
return "<b>" + func(*a, **kw) + "</b>"
return wrapper
def italic(func):
@functools.wraps(func)
def wrapper(*a, **kw):
return "<i>" + func(*a, **kw) + "</i>"
return wrapper
@bold
@italic # applied first (bottom-up)
def greet(name):
return f"Hello, {name}"
print(greet("Alice")) # <b><i>Hello, Alice</i></b>
# Class decorator
registry = []
def register(cls):
registry.append(cls)
return cls
@register
class Foo: pass
print(registry) # [<class '__main__.Foo'>]
Q516: What are @property, @staticmethod, and @classmethod?
@property turns a method into a managed attribute with optional setter/deleter. @staticmethod is a plain function namespaced inside a class with no implicit first argument. @classmethod receives the class (cls) as first argument, enabling factory methods and inheritance-aware constructors.
class Temperature:
def __init__(self, celsius):
self._celsius = celsius
@property
def fahrenheit(self):
return self._celsius * 9 / 5 + 32
@fahrenheit.setter
def fahrenheit(self, value):
self._celsius = (value - 32) * 5 / 9
@staticmethod
def absolute_zero():
return -273.15
@classmethod
def from_fahrenheit(cls, f):
return cls((f - 32) * 5 / 9)
t = Temperature.from_fahrenheit(212)
print(t.fahrenheit) # 212.0
print(Temperature.absolute_zero()) # -273.15
Q517: How do context managers work with __enter__ and __exit__?
The with statement calls __enter__ on entry and __exit__ on exit (even if an exception occurs). __exit__ receives exception info and can suppress exceptions by returning a truthy value.
class ManagedFile:
def __init__(self, path, mode):
self.path, self.mode = path, mode
def __enter__(self):
self.file = open(self.path, self.mode)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
self.file.close()
return False # don't suppress exceptions
with ManagedFile("/tmp/test.txt", "w") as f:
f.write("hello")
Q518: How does contextlib.contextmanager simplify context managers?
@contextlib.contextmanager turns a generator function into a context manager. Code before yield runs in __enter__, code after runs in __exit__. Use try/finally to guarantee cleanup.
from contextlib import contextmanager
@contextmanager
def timer():
import time
start = time.perf_counter()
try:
yield # control passes to the with-block here
finally:
elapsed = time.perf_counter() - start
print(f"Elapsed: {elapsed:.4f}s")
with timer():
sum(range(1_000_000))
Q519: How do generators work, and what are yield, send(), throw(), and close()?
A generator function returns a generator object. yield suspends execution and passes a value out. send(value) resumes and injects a value as the result of yield. throw() raises an exception at the yield point. close() throws GeneratorExit.
def echo():
while True:
received = yield
if received is None:
break
print(f"Echo: {received}")
g = echo()
next(g) # prime the generator
g.send("hello") # Echo: hello
g.send("world") # Echo: world
g.close()
Q520: What is yield from and when do you use it?
yield from iterable delegates to a sub-generator, transparently forwarding send() and throw() calls and returning the sub-generator's final return value. It is cleaner than manually iterating and re-yielding.
def flatten(nested):
for item in nested:
if isinstance(item, list):
yield from flatten(item) # recurse via yield from
else:
yield item
print(list(flatten([1, [2, [3, 4]], 5]))) # [1, 2, 3, 4, 5]
Q521: What is the difference between an iterator and an iterable?
An iterable implements __iter__() and returns an iterator. An iterator implements both __iter__() (returning itself) and __next__() (returning the next value or raising StopIteration). Lists are iterables but not iterators; iter(list) creates an iterator from one.
class Countdown:
def __init__(self, n):
self.n = n
def __iter__(self):
return self # iterator returns itself
def __next__(self):
if self.n <= 0:
raise StopIteration
self.n -= 1
return self.n + 1
for x in Countdown(3):
print(x) # 3, 2, 1
Q522: What are the most useful itertools functions?
itertools provides memory-efficient combinatorial and sequence utilities. Key ones: chain (concatenate iterables), islice (lazy slice), groupby (group consecutive elements), product (Cartesian product), combinations/permutations.
import itertools
# chain — flatten one level
print(list(itertools.chain([1, 2], [3, 4]))) # [1, 2, 3, 4]
# islice — lazy slice without materializing
print(list(itertools.islice(range(100), 5))) # [0, 1, 2, 3, 4]
# groupby — requires sorted input for global grouping
data = [("a", 1), ("a", 2), ("b", 3)]
for key, group in itertools.groupby(data, key=lambda x: x[0]):
print(key, list(group))
# product — Cartesian product
print(list(itertools.product("AB", repeat=2))) # AA, AB, BA, BB
Q523: What does functools.lru_cache do and when should you use it?
lru_cache(maxsize=N) memoizes function results in a Least-Recently-Used cache. It is useful for pure, deterministic functions with repeated calls and hashable arguments. Use maxsize=None (or @cache in Python 3.9+) for unbounded caching.
from functools import lru_cache
@lru_cache(maxsize=128)
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(50)) # fast due to caching
print(fib.cache_info()) # CacheInfo(hits=..., misses=..., maxsize=128, currsize=...)
fib.cache_clear() # invalidate all cached results
Q524: What is functools.partial and what is it useful for?
functools.partial creates a new callable with some arguments pre-filled. It is useful for adapting functions to interfaces that expect fewer arguments, and for creating specialized versions of generic functions.
from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
cube = partial(power, exponent=3)
print(square(5)) # 25
print(cube(3)) # 27
# Useful for callbacks
double = partial(map, lambda x: x * 2)
print(list(double([1, 2, 3]))) # [2, 4, 6]
Q525: How does functools.singledispatch enable function overloading?
@singledispatch dispatches a function call to different implementations based on the type of the first argument. Register type-specific implementations with @func.register.
from functools import singledispatch
@singledispatch
def process(value):
raise TypeError(f"Unsupported type: {type(value)}")
@process.register(int)
def _(value):
return f"Integer: {value * 2}"
@process.register(str)
def _(value):
return f"String: {value.upper()}"
@process.register(list)
def _(value):
return f"List with {len(value)} items"
print(process(5)) # Integer: 10
print(process("hello")) # String: HELLO
print(process([1, 2, 3])) # List with 3 items
Q526: What are __slots__ and how do they optimize memory?
By default, Python stores instance attributes in a __dict__ per object. __slots__ replaces this with a fixed-size structure, saving memory (no dict overhead) and slightly speeding up attribute access. The tradeoff is that you cannot add arbitrary attributes.
class WithDict:
def __init__(self, x, y):
self.x, self.y = x, y
class WithSlots:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x, self.y = x, y
import sys
a = WithDict(1, 2)
b = WithSlots(1, 2)
print(sys.getsizeof(a.__dict__)) # ~232 bytes (dict overhead)
# b has no __dict__ — slots use ~40-56 bytes per object instead
Q527: What are the string formatting options and their performance differences?
Python has four main formatting styles. F-strings are the fastest and most readable for runtime values. str.format() is flexible. %-style is legacy. Template strings are safe for untrusted input.
name, value = "Alice", 42
# f-string (Python 3.6+) — fastest, most readable
print(f"Hello, {name}! Value: {value:.2f}")
# str.format() — flexible, supports index/key access
print("Hello, {}! Value: {:.2f}".format(name, value))
# %-style — legacy C-style formatting
print("Hello, %s! Value: %.2f" % (name, value))
# Template strings — safe for untrusted input (no code execution)
from string import Template
t = Template("Hello, $name!")
print(t.substitute(name=name))
# f-string debugging (Python 3.8+)
print(f"{name=}, {value=}") # name='Alice', value=42
Q528: What is the difference between bytes, str, and bytearray?
str is an immutable sequence of Unicode code points. bytes is an immutable sequence of bytes (0-255). bytearray is a mutable bytes sequence. Network I/O and file I/O deal in bytes; use .encode()/.decode() to convert.
s = "hello"
b = s.encode("utf-8") # bytes: b'hello'
ba = bytearray(b) # bytearray: mutable copy
ba[0] = ord("H") # modify in place
print(ba.decode("utf-8")) # "Hello"
# bytes are immutable
try:
b[0] = 72
except TypeError as e:
print(e) # 'bytes' object does not support item assignment
Q529: What does the collections module provide?
collections offers specialized container types: defaultdict (auto-creates missing keys), Counter (counting), deque (O(1) appends/pops on both ends), OrderedDict (insertion-ordered), namedtuple (lightweight immutable records), and ChainMap (layered dict lookups).
from collections import defaultdict, Counter, deque, namedtuple, ChainMap
# defaultdict
word_count = defaultdict(int)
for word in "the quick brown fox the fox".split():
word_count[word] += 1
# Counter
freq = Counter("abracadabra")
print(freq.most_common(3)) # [('a', 5), ('b', 2), ('r', 2)]
# deque — efficient queue
q = deque([1, 2, 3], maxlen=5)
q.appendleft(0)
# namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(1, 2)
print(p.x, p.y)
# ChainMap — layered lookups
defaults = {"color": "red", "user": "guest"}
env = {"user": "admin"}
merged = ChainMap(env, defaults)
print(merged["user"]) # admin
print(merged["color"]) # red
Q530: What are Python descriptors and how do __get__, __set__, __delete__ work?
A descriptor is any object that defines __get__, __set__, or __delete__. Descriptors are the mechanism behind @property, @staticmethod, @classmethod, and ORM field objects. Data descriptors (defining both __get__ and __set__) take priority over instance __dict__.
class Validator:
"""A descriptor that enforces a minimum value."""
def __set_name__(self, owner, name):
self.name = name
self.private = f"_{name}"
def __get__(self, obj, objtype=None):
if obj is None:
return self # accessed on the class
return getattr(obj, self.private, None)
def __set__(self, obj, value):
if value < 0:
raise ValueError(f"{self.name} must be non-negative")
setattr(obj, self.private, value)
class Item:
price = Validator()
quantity = Validator()
def __init__(self, price, quantity):
self.price = price
self.quantity = quantity
item = Item(10, 5)
print(item.price) # 10
Q531: What is the difference between data and non-data descriptors?
A data descriptor defines __set__ (and optionally __delete__) in addition to __get__. It takes precedence over the instance __dict__. A non-data descriptor defines only __get__ — the instance __dict__ takes precedence over it. @property is a data descriptor; regular methods are non-data descriptors.
class NonData:
def __get__(self, obj, objtype=None):
return "non-data descriptor"
class MyClass:
attr = NonData()
obj = MyClass()
obj.__dict__["attr"] = "instance value"
print(obj.attr) # "instance value" — instance dict wins
class Data:
def __get__(self, obj, objtype=None):
return "data descriptor"
def __set__(self, obj, value):
pass # ignores the assignment
class MyClass2:
attr = Data()
obj2 = MyClass2()
obj2.__dict__["attr"] = "instance value"
print(obj2.attr) # "data descriptor" — descriptor wins
Q532: What are metaclasses and how do you use type to create classes dynamically?
Every class in Python is an instance of a metaclass (by default, type). type(name, bases, namespace) creates a class at runtime. Custom metaclasses intercept class creation to enforce constraints, register subclasses, or inject methods.
# Dynamic class creation with type()
Dog = type("Dog", (object,), {
"sound": "woof",
"speak": lambda self: self.sound,
})
print(Dog().speak()) # woof
# Custom metaclass
class SingletonMeta(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super().__call__(*args, **kwargs)
return cls._instances[cls]
class Database(metaclass=SingletonMeta):
pass
db1 = Database()
db2 = Database()
print(db1 is db2) # True
Q533: What is __init_subclass__ and how does it replace simple metaclasses?
__init_subclass__ is called on a base class whenever a new subclass is created. It provides a simpler hook than a full metaclass for enforcing rules or registering subclasses.
class PluginBase:
_registry = {}
def __init_subclass__(cls, plugin_name=None, **kwargs):
super().__init_subclass__(**kwargs)
if plugin_name:
PluginBase._registry[plugin_name] = cls
class CSVPlugin(PluginBase, plugin_name="csv"):
pass
class JSONPlugin(PluginBase, plugin_name="json"):
pass
print(PluginBase._registry)
# {'csv': <class 'CSVPlugin'>, 'json': <class 'JSONPlugin'>}
Q534: What are Abstract Base Classes (ABCs) and why use them?
abc.ABC and @abstractmethod define interfaces that subclasses must implement. Attempting to instantiate a class with unimplemented abstract methods raises TypeError. ABCs also support register() for virtual subclasses.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self) -> float: ...
@abstractmethod
def perimeter(self) -> float: ...
class Circle(Shape):
def __init__(self, r):
self.r = r
def area(self):
import math
return math.pi * self.r ** 2
def perimeter(self):
import math
return 2 * math.pi * self.r
# Shape() # TypeError — can't instantiate abstract class
c = Circle(5)
print(isinstance(c, Shape)) # True
Q535: What is Python's MRO (Method Resolution Order) and C3 linearization?
MRO determines the order Python searches classes for a method in multiple inheritance. Python uses the C3 linearization algorithm, accessible via ClassName.__mro__. The rule: a class always comes before its parents, and the order of parents is preserved.
class A:
def method(self): return "A"
class B(A):
def method(self): return "B"
class C(A):
def method(self): return "C"
class D(B, C): # MRO: D -> B -> C -> A
pass
print(D.__mro__)
# (<class 'D'>, <class 'B'>, <class 'C'>, <class 'A'>, <class 'object'>)
print(D().method()) # "B" — B comes before C in MRO
# super() respects MRO — important for cooperative multiple inheritance
class Base:
def hello(self): print("Base")
class X(Base):
def hello(self):
super().hello()
print("X")
class Y(Base):
def hello(self):
super().hello()
print("Y")
class Z(X, Y):
def hello(self):
super().hello()
print("Z")
Z().hello() # Base, Y, X, Z
Q536: What are dataclasses and what do field(), __post_init__, and frozen=True do?
@dataclass auto-generates __init__, __repr__, and __eq__. field() customizes individual fields (default factories, exclusion from comparisons). __post_init__ runs after the generated __init__. frozen=True makes instances immutable and adds __hash__.
from dataclasses import dataclass, field
@dataclass(frozen=True, order=True)
class Point:
x: float
y: float
label: str = field(default="", compare=False, repr=False)
def __post_init__(self):
# Validate after init
if self.x < 0 or self.y < 0:
raise ValueError("coordinates must be non-negative")
p1 = Point(1.0, 2.0)
p2 = Point(1.0, 2.0)
print(p1 == p2) # True
print(p1 < Point(2.0, 3.0)) # True — order=True enables <, >, etc.
print(hash(p1)) # hashable because frozen=True
Q537: What is Python's typing module and what are TypeVar, Generic, and Protocol?
TypeVar parameterizes generic types. Generic[T] creates type-parameterized classes. Protocol enables structural subtyping (duck typing with static type checking) — a class satisfies a Protocol without inheriting from it.
from typing import TypeVar, Generic, Protocol
T = TypeVar("T")
class Stack(Generic[T]):
def __init__(self) -> None:
self._items: list[T] = []
def push(self, item: T) -> None:
self._items.append(item)
def pop(self) -> T:
return self._items.pop()
# Protocol — structural subtyping
class Drawable(Protocol):
def draw(self) -> str: ...
class Circle:
def draw(self) -> str:
return "O"
def render(shape: Drawable) -> str:
return shape.draw()
print(render(Circle())) # "O" — Circle satisfies Drawable without inheriting it
Q538: What is structural subtyping with Protocol vs nominal subtyping?
Nominal subtyping requires explicit inheritance (class Foo(Bar)). Structural subtyping (via Protocol) checks only that the required methods/attributes exist, enabling duck-typing-compatible static analysis without coupling to a base class.
from typing import Protocol, runtime_checkable
@runtime_checkable
class Closeable(Protocol):
def close(self) -> None: ...
class File:
def close(self): print("file closed")
class Connection:
def close(self): print("connection closed")
def shutdown(resource: Closeable) -> None:
resource.close()
shutdown(File()) # works — no inheritance needed
shutdown(Connection()) # works
print(isinstance(File(), Closeable)) # True — runtime_checkable enables isinstance
Q539: What are TypedDict, Literal, Final, and Annotated?
TypedDict describes dict shapes with fixed string keys and typed values. Literal restricts a type to specific values. Final marks a variable as constant. Annotated attaches metadata to types for use by validation libraries or custom tools.
from typing import TypedDict, Literal, Final, Annotated
class UserRecord(TypedDict):
name: str
role: Literal["admin", "user", "guest"]
age: int
MAX_RETRIES: Final = 3
def greet(role: Literal["admin", "user"]) -> str:
return f"Hello, {role}"
# Annotated — metadata for tools like Pydantic or FastAPI
PositiveInt = Annotated[int, "must be > 0"]
user: UserRecord = {"name": "Alice", "role": "admin", "age": 30}
Q540: What are ParamSpec and Concatenate in typing?
ParamSpec captures the parameter specification of a callable, enabling typed decorators that preserve the wrapped function's signature. Concatenate[X, P] prepends additional parameters to a ParamSpec.
from typing import ParamSpec, Callable, TypeVar
import functools
P = ParamSpec("P")
R = TypeVar("R")
def log_calls(func: Callable[P, R]) -> Callable[P, R]:
@functools.wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
print(f"Calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
@log_calls
def add(x: int, y: int) -> int:
return x + y
result = add(1, 2) # type checker knows result is int
Q541: What is Python's GIL, why does it exist, and when does it matter?
The Global Interpreter Lock (GIL) is a mutex in CPython that allows only one thread to execute Python bytecode at a time. It exists to protect CPython's reference-counted memory management from race conditions. The GIL matters most for CPU-bound multi-threaded code (use multiprocessing instead). I/O-bound code releases the GIL during blocking calls, so threading works well there.
# CPU-bound — threading does NOT help due to GIL
def count(n):
while n > 0:
n -= 1
# For CPU-bound parallelism, use multiprocessing
from multiprocessing import Pool
def square(x):
return x * x
with Pool(4) as p:
print(p.map(square, range(10)))
# Python 3.13+ offers a "no-GIL" experimental build (PEP 703)
# gil=True/False in thread creation is available in that build
Q542: When should you use threading vs multiprocessing vs asyncio?
Use threading for I/O-bound tasks where the GIL is released (network, disk). Use multiprocessing for CPU-bound tasks to bypass the GIL with separate processes. Use asyncio for high-concurrency I/O where many tasks spend time waiting — it is single-threaded and has lower overhead than threads.
# threading — I/O-bound (e.g., many HTTP requests)
from threading import Thread
# multiprocessing — CPU-bound (e.g., image processing)
from multiprocessing import Process
# asyncio — high-concurrency I/O (e.g., 10,000 connections)
import asyncio
async def fetch(url: str) -> str:
import aiohttp
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.text()
# Rule of thumb:
# CPU-bound → multiprocessing
# I/O-bound, few → threading
# I/O-bound, many → asyncio
Q543: How does concurrent.futures work with ThreadPoolExecutor and ProcessPoolExecutor?
concurrent.futures provides a high-level interface. Both executors share the same API. submit() returns a Future. as_completed() yields futures as they finish. map() returns results in submission order.
from concurrent.futures import ThreadPoolExecutor, as_completed
import urllib.request
def fetch(url):
with urllib.request.urlopen(url, timeout=5) as r:
return len(r.read())
urls = ["https://example.com", "https://python.org"]
with ThreadPoolExecutor(max_workers=4) as executor:
futures = {executor.submit(fetch, url): url for url in urls}
for future in as_completed(futures):
url = futures[future]
try:
size = future.result()
print(f"{url}: {size} bytes")
except Exception as e:
print(f"{url} failed: {e}")
Q544: How does asyncio's event loop work, and what is the difference between tasks and coroutines?
The event loop runs coroutines cooperatively. A coroutine is a function defined with async def — it is not running until scheduled. A Task wraps a coroutine and schedules it immediately. asyncio.gather() runs tasks concurrently. asyncio.wait() provides more control.
import asyncio
async def work(name, delay):
print(f"{name} starting")
await asyncio.sleep(delay) # yields control to event loop
print(f"{name} done")
return name
async def main():
# gather — run concurrently, return when all done
results = await asyncio.gather(
work("A", 1),
work("B", 0.5),
work("C", 0.2),
)
print(results) # ['A', 'B', 'C'] — order of inputs, not completion
asyncio.run(main())
Q545: What are async with and async for?
async with calls __aenter__ and __aexit__ using await, enabling non-blocking resource acquisition. async for calls __aiter__ and __anext__ with await, enabling iteration over async data sources such as database cursors or WebSocket streams.
import asyncio
class AsyncTimer:
async def __aenter__(self):
self.start = asyncio.get_event_loop().time()
return self
async def __aexit__(self, *_):
elapsed = asyncio.get_event_loop().time() - self.start
print(f"Elapsed: {elapsed:.4f}s")
class AsyncRange:
def __init__(self, n):
self.n, self.i = n, 0
def __aiter__(self):
return self
async def __anext__(self):
if self.i >= self.n:
raise StopAsyncIteration
await asyncio.sleep(0) # yield to event loop
self.i += 1
return self.i - 1
async def main():
async with AsyncTimer():
async for i in AsyncRange(3):
print(i)
asyncio.run(main())
Q546: How does Python's memory management work — reference counting and the GC?
CPython uses reference counting as its primary memory management strategy. When an object's reference count drops to zero, it is immediately deallocated. The gc module handles cyclic references that reference counting cannot collect. The GC runs periodically in three generations.
import sys, gc
a = [1, 2, 3]
print(sys.getrefcount(a)) # 2 (a + the getrefcount argument)
b = a
print(sys.getrefcount(a)) # 3
del b
print(sys.getrefcount(a)) # 2
# Cyclic reference — reference count never reaches 0
x = []
x.append(x) # x references itself
del x # reference count drops to 1, not 0 — needs gc
gc.collect() # manually trigger garbage collection
print(gc.get_count()) # (gen0, gen1, gen2) object counts
Q547: What are weak references and when do you use them?
Weak references do not increment an object's reference count. The object can be garbage-collected even if weak references exist. Useful for caches and observer patterns where you don't want to keep objects alive artificially.
import weakref
class ExpensiveObject:
def __del__(self):
print("Destroyed!")
obj = ExpensiveObject()
ref = weakref.ref(obj)
print(ref()) # <ExpensiveObject ...> — alive
del obj
print(ref()) # None — object has been collected
# WeakValueDictionary — cache that doesn't prevent GC
cache = weakref.WeakValueDictionary()
data = ExpensiveObject()
cache["key"] = data
del data # removed from cache automatically when GC'd
Q548: How do you profile memory usage with sys.getsizeof, tracemalloc, and objgraph?
sys.getsizeof() returns an object's shallow size in bytes. tracemalloc tracks Python memory allocations with file/line snapshots. objgraph (third-party) shows object reference graphs and growth patterns.
import sys, tracemalloc
# Shallow size — does not include referenced objects
print(sys.getsizeof([])) # 56 bytes
print(sys.getsizeof([1, 2, 3])) # 88 bytes
# tracemalloc — find memory leaks
tracemalloc.start()
big_list = [dict(i=i) for i in range(10000)]
snapshot = tracemalloc.take_snapshot()
top = snapshot.statistics("lineno")[:3]
for stat in top:
print(stat)
del big_list
tracemalloc.stop()
Q549: What is Python bytecode and how does the dis module help?
Python compiles source to bytecode (.pyc files), which is executed by the CPython virtual machine. The dis module disassembles bytecode into human-readable instructions. Understanding bytecode helps explain performance characteristics.
import dis
def add(a, b):
return a + b
dis.dis(add)
# LOAD_FAST 0 (a)
# LOAD_FAST 1 (b)
# BINARY_OP 0 (+)
# RETURN_VALUE
# Code object attributes
print(add.__code__.co_varnames) # ('a', 'b')
print(add.__code__.co_consts) # (None,)
print(add.__code__.co_filename) # source file
Q550: How do dynamic imports work with importlib and sys.modules?
importlib.import_module() imports by string name at runtime. sys.modules is a cache of imported modules — if a module is already there, Python skips re-executing it. You can reload a module with importlib.reload().
import importlib, sys
# Dynamic import
math = importlib.import_module("math")
print(math.sqrt(16)) # 4.0
# Conditional import
try:
ujson = importlib.import_module("ujson")
except ImportError:
import json as ujson
# Inspect the module cache
print("json" in sys.modules) # True after import
# Reload a module (picks up changes without restarting)
importlib.reload(importlib) # rarely needed; useful in REPL
Q551: What are namedtuple, dataclass, TypedDict, and attrs — and when do you choose each?
Each serves different tradeoffs between immutability, mutability, memory, and type-checking integration.
# namedtuple — immutable, memory-efficient, tuple-compatible
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
# dataclass — mutable by default, full class features
from dataclasses import dataclass
@dataclass
class Config:
host: str
port: int = 8080
# TypedDict — type annotations on plain dicts, no runtime enforcement
from typing import TypedDict
class Headers(TypedDict):
content_type: str
authorization: str
# Decision guide:
# Need tuple interop or immutability → namedtuple
# Need mutable class with validation → dataclass
# Working with dicts, want type hints → TypedDict
# Need validators/converters/slots out of box → attrs (third-party)
Q552: What is __all__ and how does it control module exports?
__all__ is a list of public names exported when from module import * is used. It also serves as documentation — telling readers which symbols are part of the public API. Names not in __all__ can still be imported explicitly.
# mymodule.py
__all__ = ["public_func", "PublicClass"]
def public_func():
return "public"
def _private_func(): # not exported by *
return "private"
class PublicClass:
pass
class _InternalClass: # not exported by *
pass
# User code:
# from mymodule import * → imports only public_func, PublicClass
# from mymodule import _private_func → still works explicitly
Q553: What are __init__.py patterns and namespace packages?
__init__.py marks a directory as a package and runs on import. It can re-export symbols, set __all__, and initialize package state. Namespace packages (PEP 420, Python 3.3+) allow packages split across multiple directories without __init__.py.
# mypackage/__init__.py — re-export public API
from .utils import helper
from .models import User
__all__ = ["helper", "User"]
# Lazy imports in __init__.py for large packages
def __getattr__(name):
if name == "heavy_module":
import importlib
return importlib.import_module(".heavy_module", __name__)
raise AttributeError(f"module has no attribute {name!r}")
# Namespace package — no __init__.py needed
# /site-a/mynamespace/foo.py
# /site-b/mynamespace/bar.py
# Both importable as: mynamespace.foo, mynamespace.bar
Q554: How does match/case pattern matching work in Python 3.10+?
match/case is structural pattern matching. Unlike a switch statement, it can destructure objects, sequences, mappings, and class instances. Patterns are matched top to bottom; the first match wins.
def handle_command(command):
match command.split():
case ["quit"]:
return "Quitting"
case ["go", direction] if direction in ("north", "south"):
return f"Going {direction}"
case ["pick", "up", item]:
return f"Picking up {item}"
case ["drop", *items]:
return f"Dropping {items}"
case _:
return f"Unknown command: {command}"
print(handle_command("go north")) # Going north
print(handle_command("pick up key")) # Picking up key
# Class pattern matching
from dataclasses import dataclass
@dataclass
class Point:
x: int; y: int
def classify(point):
match point:
case Point(x=0, y=0): return "Origin"
case Point(x=0, y=_): return "Y axis"
case Point(x=_, y=0): return "X axis"
case _: return "Other"
Q555: What are Exception Groups and ExceptionGroup (Python 3.11+)?
ExceptionGroup bundles multiple exceptions together, introduced for structured concurrency use-cases (like asyncio.TaskGroup). except* syntax handles specific sub-exceptions within a group while allowing others to propagate.
import asyncio
async def fail(msg):
raise ValueError(msg)
async def main():
try:
async with asyncio.TaskGroup() as tg:
tg.create_task(fail("error 1"))
tg.create_task(fail("error 2"))
except* ValueError as eg:
for exc in eg.exceptions:
print(f"Caught: {exc}")
asyncio.run(main())
# Caught: error 1
# Caught: error 2
# Manual ExceptionGroup
try:
raise ExceptionGroup("multiple failures", [
ValueError("v"),
TypeError("t"),
])
except* ValueError as eg:
print("Handled ValueErrors:", eg.exceptions)
Q556: What is the walrus operator := and when should you use it?
The walrus operator (assignment expression, PEP 572) assigns a value within an expression, avoiding repeated computation. Use it in while loops, comprehensions, and if statements when you need the value both for testing and for use.
import re
# Avoid computing match twice or using a temp variable
line = "2024-01-15: deployment successful"
if m := re.match(r"(\d{4}-\d{2}-\d{2}): (.+)", line):
date, event = m.group(1), m.group(2)
print(f"Date: {date}, Event: {event}")
# In while loop — clean file reading
# while chunk := file.read(8192):
# process(chunk)
# In comprehension — reuse intermediate computation
results = [y for x in range(10) if (y := x ** 2) > 10]
print(results) # [16, 25, 36, 49, 64, 81]
Q557: What is zip(strict=True) and how does zip_longest differ?
zip(strict=True) (Python 3.10+) raises ValueError if iterables have different lengths, preventing silently dropped data. itertools.zip_longest pads shorter iterables with a fill value instead of truncating.
from itertools import zip_longest
# zip — truncates at shortest
print(list(zip([1, 2, 3], ["a", "b"]))) # [(1,'a'), (2,'b')]
# zip(strict=True) — raises ValueError on length mismatch
try:
list(zip([1, 2, 3], ["a", "b"], strict=True))
except ValueError as e:
print(e) # zip() has arguments with different lengths
# zip_longest — pads with fill value
print(list(zip_longest([1, 2, 3], ["a", "b"], fillvalue=None)))
# [(1, 'a'), (2, 'b'), (3, None)]
Q558: What is exception chaining with raise X from Y?
raise X from Y explicitly chains exceptions, setting X.__cause__ = Y. Python also implicitly chains exceptions when a second exception is raised during exception handling via __context__. Use raise X from None to suppress the chain.
def connect(host):
raise OSError("network unreachable")
def load_config(path):
try:
connect("db.example.com")
except OSError as e:
raise RuntimeError("failed to load config") from e # explicit chain
try:
load_config("/etc/app.conf")
except RuntimeError as e:
print(e) # failed to load config
print(e.__cause__) # network unreachable
# Suppress chain
# raise ValueError("bad input") from None
Q559: What is the else clause in try blocks and how does finally differ?
The else block runs only when no exception was raised in the try block — useful for code that should only run on success but should not suppress exceptions. finally always runs, regardless of whether an exception occurred.
def read_file(path):
try:
f = open(path)
except FileNotFoundError:
print("File not found")
return None
else:
# runs only if open() succeeded
data = f.read()
f.close()
return data
finally:
# ALWAYS runs — good for cleanup/logging
print("read_file complete")
# else prevents accidentally catching exceptions from the success path
# finally ensures resources are released even on unexpected errors
Q560: What are __future__ annotations and PEP 563 deferred evaluation?
from __future__ import annotations makes all annotations strings (lazy), avoiding NameError for forward references and speeding up import. This is the default in Python 3.14+. Use typing.get_type_hints() to resolve them at runtime.
from __future__ import annotations
from typing import get_type_hints
class Node:
def __init__(self, value: int, next: Node | None = None):
# Without __future__ annotations, "Node" would be NameError here
self.value = value
self.next = next
# Annotations are stored as strings
print(Node.__init__.__annotations__)
# {'value': 'int', 'next': 'Node | None', 'return': 'None'}
# Resolve at runtime if needed
hints = get_type_hints(Node.__init__, localns={"Node": Node})
print(hints)
Q561: What is the difference between @cache, @lru_cache, and @cached_property?
@functools.cache (Python 3.9+) is an unbounded lru_cache with simpler semantics. @lru_cache(maxsize=N) bounds the cache, evicting least-recently-used entries. @functools.cached_property computes a property once per instance and caches the result in the instance's __dict__.
from functools import cache, lru_cache, cached_property
@cache # unbounded memoization
def fib(n: int) -> int:
return n if n < 2 else fib(n-1) + fib(n-2)
@lru_cache(maxsize=64) # bounded — evicts LRU entries
def get_user(user_id: int): ...
class Config:
@cached_property # computed once per instance, stored in __dict__
def settings(self) -> dict:
print("Loading settings...")
return {"debug": False}
c = Config()
print(c.settings) # "Loading settings..." printed
print(c.settings) # cached — no print
Q562: How does functools.reduce work and when is it appropriate?
reduce(func, iterable, initializer) applies a two-argument function cumulatively, reducing the iterable to a single value. It is appropriate for fold operations (e.g., product, union, accumulation) but often less readable than an explicit loop.
from functools import reduce
import operator
# Sum using reduce (prefer sum() in practice)
total = reduce(operator.add, [1, 2, 3, 4, 5], 0) # 15
# Product
product = reduce(operator.mul, range(1, 6), 1) # 120 (5!)
# Flatten a list of lists
nested = [[1, 2], [3, 4], [5, 6]]
flat = reduce(lambda acc, x: acc + x, nested, [])
print(flat) # [1, 2, 3, 4, 5, 6]
# Prefer itertools.chain.from_iterable for flattening in practice
import itertools
flat2 = list(itertools.chain.from_iterable(nested))
Q563: What is the RAII pattern and how does Python's with statement approximate it?
RAII (Resource Acquisition Is Initialization) ties resource lifetime to object lifetime. Python's with statement approximates it: resources are acquired in __enter__ and released in __exit__, even if exceptions occur. Unlike true RAII (C++), Python relies on explicit with blocks rather than destructor guarantees.
# File — classic RAII via context manager
with open("data.txt", "w") as f:
f.write("hello")
# file is closed here regardless of exceptions
# Lock — prevents deadlocks
import threading
lock = threading.Lock()
with lock:
pass # critical section
# The with statement is safer than try/finally for resource management
# __del__ is NOT reliable for cleanup (GC timing is non-deterministic)
Q564: What is tomllib and how do you parse TOML config files in Python 3.11+?
tomllib (Python 3.11+, PEP 680) provides a standard TOML parser. TOML is a configuration format designed to be readable and to map unambiguously to a hash table. For writing TOML, use the third-party tomli_w package.
import tomllib
# Reading a pyproject.toml
with open("pyproject.toml", "rb") as f: # must open in binary mode
config = tomllib.load(f)
print(config["project"]["name"])
print(config["project"]["version"])
# Parsing from a string
toml_bytes = b"""
[server]
host = "localhost"
port = 8080
[database]
url = "postgresql://localhost/mydb"
pool_size = 10
"""
data = tomllib.loads(toml_bytes.decode())
print(data["server"]["port"]) # 8080
Q565: How do you write a non-data descriptor to implement method binding?
Python's method objects are non-data descriptors. When you access obj.method, function.__get__(obj, type(obj)) is called, returning a bound method. You can replicate this to understand how methods work.
class BoundMethod:
def __init__(self, func, instance):
self.func, self.instance = func, instance
def __call__(self, *args, **kwargs):
return self.func(self.instance, *args, **kwargs)
class MyDescriptor:
def __init__(self, func):
self.func = func
def __get__(self, obj, objtype=None):
if obj is None:
return self # class access — return descriptor
return BoundMethod(self.func, obj) # instance access — bound method
class Greeter:
@MyDescriptor
def greet(self, name):
return f"Hello, {name} from {self}"
g = Greeter()
print(g.greet("Alice")) # Hello, Alice from <Greeter...>
Q566: What is __class_getitem__ and how does it support runtime generics?
__class_getitem__ is called when you subscript a class (MyClass[T]), enabling generic aliases for type hints. Built-in types like list, dict, and tuple use this to support list[int] syntax in Python 3.9+.
class TypedStack:
def __class_getitem__(cls, item_type):
class _TypedStack(list):
_type = item_type
def append(self, value):
if not isinstance(value, self._type):
raise TypeError(f"Expected {self._type.__name__}")
super().append(value)
_TypedStack.__name__ = f"TypedStack[{item_type.__name__}]"
return _TypedStack
IntStack = TypedStack[int]
s = IntStack()
s.append(1) # OK
try:
s.append("x") # TypeError
except TypeError as e:
print(e)
# Built-in generics (Python 3.9+)
x: list[int] = [1, 2, 3]
y: dict[str, int] = {"a": 1}
Q567: How do you implement a thread-safe singleton using a metaclass or a module?
The simplest singleton in Python is a module — modules are imported once and cached in sys.modules. For class-based singletons, use a lock to prevent race conditions in multi-threaded contexts.
import threading
class SingletonMeta(type):
_instances = {}
_lock = threading.Lock()
def __call__(cls, *args, **kwargs):
with cls._lock:
if cls not in cls._instances:
instance = super().__call__(*args, **kwargs)
cls._instances[cls] = instance
return cls._instances[cls]
class AppConfig(metaclass=SingletonMeta):
def __init__(self):
self.debug = False
c1 = AppConfig()
c2 = AppConfig()
print(c1 is c2) # True
# Module-level singleton (simpler and idiomatic):
# config.py → class _Config: ...; instance = _Config()
# users import: from config import instance
Q568: What is cooperative multiple inheritance and why must you use super() consistently?
In cooperative multiple inheritance, all classes in the MRO must use super() so that the chain is not broken. If one class calls the parent directly (Parent.method(self)), intermediate classes in the MRO are skipped.
class Base:
def setup(self):
print("Base.setup")
class LogMixin:
def setup(self):
print("LogMixin.setup")
super().setup() # must call super() to continue MRO chain
class CacheMixin:
def setup(self):
print("CacheMixin.setup")
super().setup() # must call super() to continue MRO chain
class Service(LogMixin, CacheMixin, Base):
def setup(self):
print("Service.setup")
super().setup()
Service().setup()
# Service.setup
# LogMixin.setup
# CacheMixin.setup
# Base.setup
Q569: How does Python's gc module work and how do you detect cyclic references?
The garbage collector supplements reference counting by detecting reference cycles. It operates on three generations. Objects that survive collection are promoted to older generations. gc.get_referrers() and gc.get_referents() help diagnose cycles.
import gc
class Node:
def __init__(self, val):
self.val = val
self.next = None
a = Node(1)
b = Node(2)
a.next = b
b.next = a # cycle: a -> b -> a
gc.disable()
del a, b # reference counts don't reach 0 due to cycle
gc.enable()
collected = gc.collect()
print(f"Collected {collected} objects")
# Save uncollectable objects for inspection
gc.set_debug(gc.DEBUG_SAVEALL)
Q570: What is __set_name__ in descriptors and how does it help?
__set_name__(owner, name) is called when a descriptor is assigned to a class attribute. It receives the owning class and the attribute name, allowing the descriptor to store the name for error messages and internal storage — without the user having to repeat the name.
class TypedField:
def __set_name__(self, owner, name):
self.name = name
self.storage = f"_{name}"
def __init__(self, expected_type):
self.expected_type = expected_type
def __get__(self, obj, objtype=None):
if obj is None: return self
return getattr(obj, self.storage, None)
def __set__(self, obj, value):
if not isinstance(value, self.expected_type):
raise TypeError(
f"{self.name} must be {self.expected_type.__name__}, "
f"got {type(value).__name__}"
)
setattr(obj, self.storage, value)
class Person:
name = TypedField(str)
age = TypedField(int)
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Alice", 30)
print(p.name, p.age)
Q571: How do you use __new__ and when is it needed over __init__?
__new__ creates and returns the instance; __init__ initializes it. __new__ is needed when subclassing immutable types (int, str, tuple) or implementing singletons, as these cannot be modified in __init__.
class UpperStr(str):
def __new__(cls, value):
# __init__ is too late — str is immutable
return super().__new__(cls, value.upper())
print(UpperStr("hello")) # HELLO
# Singleton via __new__
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
a = Singleton()
b = Singleton()
print(a is b) # True
Q572: What is @dataclass(kw_only=True) and when is it useful?
kw_only=True (Python 3.10+) requires all fields to be passed as keyword arguments. This avoids positional argument ordering issues in inheritance hierarchies and makes call sites more explicit.
from dataclasses import dataclass
@dataclass(kw_only=True)
class BaseConfig:
host: str = "localhost"
port: int = 8080
@dataclass(kw_only=True)
class DatabaseConfig(BaseConfig):
name: str = "mydb"
pool_size: int = 5
# All arguments must be keyword arguments
cfg = DatabaseConfig(host="db.example.com", name="prod", pool_size=20)
print(cfg)
# DatabaseConfig(host='db.example.com', port=8080, name='prod', pool_size=20)
# Without kw_only, adding fields with defaults to a parent can break
# subclass field ordering, causing TypeError at class definition time.
Q573: What is __slots__ interaction with inheritance?
When using __slots__ with inheritance, each class should define only its own slots. Inheriting from a class without __slots__ reintroduces __dict__, negating memory savings. Proper usage requires all classes in the hierarchy to define __slots__.
class Animal:
__slots__ = ("name",)
def __init__(self, name):
self.name = name
class Dog(Animal):
__slots__ = ("breed",) # adds breed slot; name slot inherited
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
d = Dog("Rex", "Labrador")
print(d.name, d.breed)
try:
d.age = 3 # AttributeError — no __dict__, no 'age' slot
except AttributeError as e:
print(e)
Q574: What is asyncio.shield() and when should you use it?
asyncio.shield() protects a coroutine from cancellation. If the outer task is cancelled, the shielded inner task continues running. Use it when a critical operation (e.g., database write) must complete even if the requesting task is cancelled.
import asyncio
async def critical_write(data):
await asyncio.sleep(1) # simulate DB write
print(f"Written: {data}")
return True
async def handler(data):
try:
# If handler is cancelled, critical_write still completes
result = await asyncio.shield(critical_write(data))
return result
except asyncio.CancelledError:
print("Handler cancelled, but write continues...")
raise
async def main():
task = asyncio.create_task(handler("important data"))
await asyncio.sleep(0.1)
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
await asyncio.sleep(2) # wait for shielded write to complete
asyncio.run(main())
Q575: What is f"{var=}" debugging syntax and what else can f-strings do?
The = specifier in f-strings (Python 3.8+) prints both the expression and its value. F-strings also support format specs, conversions (!r, !s, !a), and arbitrary expressions.
x = 42
items = [1, 2, 3]
# Debugging with =
print(f"{x=}") # x=42
print(f"{items=}") # items=[1, 2, 3]
print(f"{len(items)=}") # len(items)=3
# Conversions
name = "cafe"
print(f"{name!r}") # 'cafe' — repr()
# Format specs
pi = 3.14159
print(f"{pi:.3f}") # 3.142
print(f"{pi:>10.2f}") # right-aligned with width
# Nested f-strings
width = 10
print(f"{'hello':>{width}}") # " hello"
Q576: How does asyncio.gather differ from asyncio.wait?
gather(*coros) runs all coroutines concurrently and returns results in the same order as inputs, raising the first exception by default. wait(tasks, ...) returns two sets (done, pending) and allows more control via return_when (e.g., FIRST_EXCEPTION, FIRST_COMPLETED).
import asyncio
async def task(n, fail=False):
await asyncio.sleep(n * 0.1)
if fail:
raise ValueError(f"task {n} failed")
return n
async def demo():
# gather — simple, returns ordered results
results = await asyncio.gather(task(1), task(2), task(3))
print(results) # [1, 2, 3]
# gather with return_exceptions=True — collect errors instead of raising
results = await asyncio.gather(
task(1), task(2, fail=True), return_exceptions=True
)
print(results) # [1, ValueError('task 2 failed')]
# wait — more control
tasks = {asyncio.create_task(task(i)) for i in range(3)}
done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
print(f"{len(done)} done, {len(pending)} pending")
asyncio.run(demo())
Q577: What is the difference between @abstractmethod and duck typing?
@abstractmethod enforces at class instantiation time that a method is implemented — a hard contract. Duck typing relies solely on the presence of the right methods at call time with no enforcement. ABCs combine both: they define an interface and optionally provide isinstance/issubclass checks via register().
from abc import ABC, abstractmethod
class Serializer(ABC):
@abstractmethod
def serialize(self, data: dict) -> str: ...
@abstractmethod
def deserialize(self, raw: str) -> dict: ...
class JSONSerializer(Serializer):
def serialize(self, data): import json; return json.dumps(data)
def deserialize(self, raw): import json; return json.loads(raw)
# Duck typing — no ABC, no enforcement
class XMLSerializer:
def serialize(self, data): return "<xml/>"
def deserialize(self, raw): return {}
# register() — virtual subclass: isinstance returns True without inheritance
Serializer.register(XMLSerializer)
print(isinstance(XMLSerializer(), Serializer)) # True
Q578: How do you design a good exception hierarchy?
A well-designed exception hierarchy uses a package-level base exception, specific subclasses, and informative __init__ methods. This allows callers to catch broadly or specifically.
class AppError(Exception):
"""Base exception for the application."""
class ValidationError(AppError):
def __init__(self, field, message):
self.field = field
self.message = message
super().__init__(f"{field}: {message}")
def __repr__(self):
return f"ValidationError(field={self.field!r}, message={self.message!r})"
class DatabaseError(AppError):
pass
class ConnectionError(DatabaseError):
pass
# Catch specifically
try:
raise ValidationError("email", "invalid format")
except ValidationError as e:
print(e.field) # email
# Catch broadly
try:
raise ConnectionError("timeout")
except AppError:
print("App-level error caught")
Q579: How does __getattr__ differ from __getattribute__?
__getattribute__ is called on every attribute access, making it easy to cause infinite recursion if you call self.x inside it. __getattr__ is only called when normal lookup fails — safer for proxy objects and lazy loading.
class LazyLoader:
"""Load modules lazily on attribute access."""
def __init__(self, module_name):
object.__setattr__(self, "_module_name", module_name)
object.__setattr__(self, "_module", None)
def __getattr__(self, name):
# called only when attribute is NOT found normally
module = object.__getattribute__(self, "_module")
if module is None:
import importlib
module = importlib.import_module(
object.__getattribute__(self, "_module_name")
)
object.__setattr__(self, "_module", module)
return getattr(module, name)
math_proxy = LazyLoader("math")
print(math_proxy.pi) # 3.141... — imports math only on first access
print(math_proxy.sqrt(16)) # 4.0
Q580: What is the __missing__ method in dict subclasses?
__missing__ is called by dict.__getitem__ when a key is not found. It is how defaultdict works. Subclassing dict and defining __missing__ is an alternative to defaultdict when you need more control.
class AutoVivification(dict):
"""Deeply nested dicts auto-created on access."""
def __missing__(self, key):
self[key] = AutoVivification()
return self[key]
tree = AutoVivification()
tree["a"]["b"]["c"] = 42
print(tree["a"]["b"]["c"]) # 42
print(tree["a"]["b"]) # {'c': 42}
# defaultdict uses __missing__ internally:
from collections import defaultdict
dd = defaultdict(list)
dd["key"].append(1) # __missing__ creates [] for "key"
print(dd) # defaultdict(<class 'list'>, {'key': [1]})
Q581: What is __call__ and how does it make objects callable?
Defining __call__ makes an instance callable like a function. This is useful for stateful callables and class-based decorators that need to hold configuration.
class Accumulator:
def __init__(self):
self.total = 0
def __call__(self, value):
self.total += value
return self.total
def reset(self):
self.total = 0
acc = Accumulator()
print(acc(10)) # 10
print(acc(5)) # 15
# Class-based decorator with configuration
class Retry:
def __init__(self, max_attempts):
self.max_attempts = max_attempts
def __call__(self, func):
import functools
@functools.wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(self.max_attempts):
try:
return func(*args, **kwargs)
except Exception:
if attempt == self.max_attempts - 1:
raise
return wrapper
@Retry(max_attempts=3)
def flaky(): ...
Q582: How does __len__, __bool__, and truthiness work in Python?
Python calls __bool__ to evaluate truth. If __bool__ is not defined, it falls back to __len__ — a container with length 0 is falsy. If neither is defined, the object is always truthy.
class SmartList:
def __init__(self, items):
self.items = list(items)
def __len__(self):
return len(self.items)
# No __bool__ needed — Python uses __len__ as fallback
sl = SmartList([])
print(bool(sl)) # False — len() == 0
sl2 = SmartList([1, 2, 3])
print(bool(sl2)) # True
class AlwaysFalsy:
def __bool__(self):
return False
af = AlwaysFalsy()
if not af:
print("falsy!") # printed
Q583: What is __contains__ and how does the in operator work?
The in operator calls __contains__. If not defined, Python falls back to iterating with __iter__ (O(n)). For O(1) membership testing, always define __contains__ on custom containers.
class RangeSet:
def __init__(self, start, stop):
self.start, self.stop = start, stop
def __contains__(self, item):
return self.start <= item < self.stop # O(1)
def __iter__(self):
return iter(range(self.start, self.stop))
r = RangeSet(1, 100)
print(50 in r) # True — uses __contains__
print(200 in r) # False
# Without __contains__, `in` falls back to iteration (O(n)):
class SlowSet:
def __init__(self, items):
self.items = list(items)
def __iter__(self):
return iter(self.items)
# 99 in SlowSet(range(100)) — iterates through all items
Q584: How do you use __init_subclass__ to validate subclasses?
__init_subclass__ is invoked for each new subclass, making it ideal for enforcing interface requirements at class-definition time rather than at instantiation.
class Serializable:
FORMAT: str # subclasses must define this
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
if not hasattr(cls, "FORMAT"):
raise TypeError(f"{cls.__name__} must define a FORMAT class attribute")
if not isinstance(cls.FORMAT, str):
raise TypeError("FORMAT must be a string")
class JSONRecord(Serializable):
FORMAT = "json"
class CSVRecord(Serializable):
FORMAT = "csv"
try:
class BadRecord(Serializable):
pass # missing FORMAT
except TypeError as e:
print(e) # BadRecord must define a FORMAT class attribute
Q585: What is sys.getsizeof vs object.__sizeof__ and how do you measure deep size?
sys.getsizeof() calls __sizeof__() and adds garbage collector overhead. __sizeof__ returns the raw C structure size. Neither is recursive — they measure only the object itself, not referenced objects.
import sys
lst = [1, 2, 3, 4, 5]
print(sys.getsizeof(lst)) # ~104 bytes — list header + pointers
print(sys.getsizeof(lst[0])) # 28 bytes — small int object
# Deep (recursive) size measurement
def deep_sizeof(obj, seen=None):
if seen is None: seen = set()
oid = id(obj)
if oid in seen: return 0
seen.add(oid)
size = sys.getsizeof(obj)
if hasattr(obj, "__dict__"):
size += deep_sizeof(obj.__dict__, seen)
if hasattr(obj, "__iter__") and not isinstance(obj, (str, bytes)):
for item in obj:
size += deep_sizeof(item, seen)
return size
print(deep_sizeof([1, 2, 3])) # includes referenced int objects
Q586: How does Python's enum module work and what are its variants?
enum.Enum creates symbolic constants with identity and value. Variants: IntEnum (comparable with ints), Flag/IntFlag (bitwise operations), StrEnum (Python 3.11+, string-compatible).
from enum import Enum, Flag, auto
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
print(Color.RED) # Color.RED
print(Color.RED.value) # 1
print(Color.RED is Color.RED) # True — identity guaranteed
class Permission(Flag):
READ = auto()
WRITE = auto()
EXECUTE = auto()
ALL = READ | WRITE | EXECUTE
p = Permission.READ | Permission.WRITE
print(Permission.READ in p) # True
# Enum from value
print(Color(2)) # Color.GREEN
# Iteration
for color in Color:
print(color.name, color.value)
Q587: What is the pathlib module and how does it improve path handling?
pathlib.Path provides an object-oriented API for filesystem paths. It is cross-platform, composable with the / operator, and integrates with open(), os, and shutil.
from pathlib import Path
base = Path("/tmp")
config = base / "app" / "config.toml" # cross-platform path join
print(config.name) # config.toml
print(config.stem) # config
print(config.suffix) # .toml
print(config.parent) # /tmp/app
# Create directories
config.parent.mkdir(parents=True, exist_ok=True)
# Write and read
config.write_text("[server]\nhost = 'localhost'\n")
print(config.read_text())
# Glob
src = Path(".")
for py_file in src.glob("**/*.py"):
print(py_file)
print(config.exists()) # True
print(config.is_file()) # True
Q588: What is __subclasshook__ in ABCs?
__subclasshook__ customizes isinstance/issubclass checks without requiring explicit register() calls. If it returns True, the class is considered a virtual subclass; NotImplemented falls through to normal checks.
from abc import ABC, abstractmethod
class Drawable(ABC):
@abstractmethod
def draw(self): ...
@classmethod
def __subclasshook__(cls, subclass):
if cls is Drawable:
if any("draw" in B.__dict__ for B in subclass.__mro__):
return True
return NotImplemented
class Circle:
def draw(self): return "O"
class Square:
def render(self): return "[]" # no draw method
print(isinstance(Circle(), Drawable)) # True — has draw()
print(isinstance(Square(), Drawable)) # False — no draw()
Q589: How does contextlib.suppress and contextlib.nullcontext work?
contextlib.suppress(*exceptions) is a concise way to ignore specific exceptions. contextlib.nullcontext provides a no-op context manager useful for optional context managers in conditional logic.
from contextlib import suppress, nullcontext
import os
# suppress — cleaner than try/except for single-line ignores
with suppress(FileNotFoundError):
os.remove("/tmp/nonexistent.txt") # silently ignored
# nullcontext — useful for optional context managers
def process(data, lock=None):
ctx = lock if lock is not None else nullcontext()
with ctx:
return [x * 2 for x in data]
import threading
lock = threading.Lock()
print(process([1, 2, 3], lock=lock)) # uses lock
print(process([1, 2, 3])) # no-op context
Q590: What is __format__ and how does it integrate with f-strings?
__format__(format_spec) is called when an object is used in an f-string or format() call with a format spec. Defining it allows custom formatting syntax for your types.
class Money:
def __init__(self, amount, currency="USD"):
self.amount = amount
self.currency = currency
def __format__(self, format_spec):
if format_spec == "":
return f"{self.currency} {self.amount:.2f}"
if format_spec == "short":
return f"{self.amount:.0f}{self.currency[0]}"
if format_spec.startswith("."):
decimals = int(format_spec[1:])
return f"{self.currency} {self.amount:.{decimals}f}"
return format(self.amount, format_spec)
price = Money(9.99)
print(f"{price}") # USD 9.99
print(f"{price:short}") # 10U
print(f"{price:.4f}") # USD 9.9900
Q591: How does cProfile work and when do you use sys.settrace?
cProfile is the standard deterministic profiler; it measures cumulative time per function call. sys.settrace installs a global trace function called on every line, call, and return — used internally by debuggers and coverage tools.
import cProfile, pstats, io
# Profile a function
profiler = cProfile.Profile()
profiler.enable()
result = sum(x * x for x in range(1_000_000))
profiler.disable()
stream = io.StringIO()
ps = pstats.Stats(profiler, stream=stream).sort_stats("cumulative")
ps.print_stats(10)
print(stream.getvalue())
# sys.settrace — simple line tracer
import sys
def tracer(frame, event, arg):
if event == "line":
print(f" {frame.f_lineno}: {frame.f_code.co_name}")
return tracer
def my_func():
x = 1 + 1
return x
sys.settrace(tracer)
my_func()
sys.settrace(None)
Q592: What is @functools.total_ordering and how does it simplify comparison methods?
@total_ordering generates missing comparison methods from __eq__ and one of __lt__, __le__, __gt__, __ge__. It reduces boilerplate at the cost of a slight performance penalty.
from functools import total_ordering
@total_ordering
class Version:
def __init__(self, major, minor, patch):
self.v = (major, minor, patch)
def __eq__(self, other):
return self.v == other.v
def __lt__(self, other):
return self.v < other.v
# total_ordering generates: __le__, __gt__, __ge__
v1 = Version(1, 2, 0)
v2 = Version(2, 0, 0)
print(v1 < v2) # True
print(v1 <= v2) # True — generated
print(v2 > v1) # True — generated
print(sorted([v2, v1])) # [v1, v2]
Q593: What are Python's __enter__ and __exit__ exception-suppression semantics?
If __exit__ returns a truthy value, the exception that triggered it is suppressed. If it returns False or None, the exception propagates. This allows context managers to handle certain errors gracefully.
class SuppressIO:
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is IOError:
print(f"Suppressed IOError: {exc_val}")
return True # suppress the exception
return False # let other exceptions propagate
with SuppressIO():
raise IOError("disk full")
print("Continued after suppressed IOError")
# contextlib.suppress uses the same mechanism
from contextlib import suppress
with suppress(IOError):
raise IOError("ignored")
print("Still running")
Q594: What is the __prepare__ metaclass hook?
__prepare__ returns the namespace dictionary used when executing the class body. Returning a custom mapping lets you intercept attribute assignments during class definition — used by enum.Enum to track definition order.
from collections import OrderedDict
class OrderedMeta(type):
@classmethod
def __prepare__(mcs, name, bases, **kwargs):
return OrderedDict() # custom namespace
def __new__(mcs, name, bases, namespace, **kwargs):
cls = super().__new__(mcs, name, bases, dict(namespace))
cls._fields = [k for k in namespace if not k.startswith("_")]
return cls
class Schema(metaclass=OrderedMeta):
name = str
age = int
email = str
print(Schema._fields) # ['name', 'age', 'email'] — insertion order preserved
Q595: How does asyncio.TaskGroup work in Python 3.11+?
asyncio.TaskGroup is a context manager that creates tasks and ensures all tasks are awaited. If any task raises an exception, all remaining tasks are cancelled and an ExceptionGroup is raised — providing structured concurrency.
import asyncio
async def fetch(id: int) -> str:
await asyncio.sleep(0.1 * id)
if id == 3:
raise ValueError(f"Task {id} failed")
return f"result-{id}"
async def main():
try:
async with asyncio.TaskGroup() as tg:
t1 = tg.create_task(fetch(1))
t2 = tg.create_task(fetch(2))
t3 = tg.create_task(fetch(3)) # will fail
except* ValueError as eg:
print(f"Caught: {[str(e) for e in eg.exceptions]}")
if t1.done() and not t1.cancelled():
print(t1.result()) # result-1
asyncio.run(main())
Q596: What is __class_cell__ and why must metaclasses preserve it?
__class_cell__ is a cell that provides the __class__ reference used by zero-argument super(). When writing metaclasses that manipulate the class namespace, you must not delete __class_cell__ to avoid breaking super().
class ValidMeta(type):
def __new__(mcs, name, bases, namespace, **kwargs):
# NEVER delete namespace.pop('__class_cell__') — it breaks super()
cls = super().__new__(mcs, name, bases, namespace)
return cls
class Base:
def method(self):
return "Base"
class Child(Base, metaclass=ValidMeta):
def method(self):
return super().method() + " -> Child" # works correctly
print(Child().method()) # Base -> Child
# If __class_cell__ were removed:
# RuntimeError: super(): __class__ cell not found
Q597: How do you implement a coroutine-based pipeline with asyncio.Queue?
asyncio.Queue enables producer-consumer patterns in async code. Producers put items; consumers get items. Use sentinel values or task_done()/join() to signal completion.
import asyncio
async def producer(queue: asyncio.Queue, items):
for item in items:
await queue.put(item)
print(f"Produced: {item}")
await asyncio.sleep(0.05)
await queue.put(None) # sentinel
async def consumer(queue: asyncio.Queue):
results = []
while True:
item = await queue.get()
if item is None:
break
result = item * 2
print(f"Consumed: {item} -> {result}")
results.append(result)
return results
async def main():
q = asyncio.Queue(maxsize=3)
prod = asyncio.create_task(producer(q, range(5)))
cons = asyncio.create_task(consumer(q))
await prod
results = await cons
print(results) # [0, 2, 4, 6, 8]
asyncio.run(main())
Q598: What is importlib.metadata and how do you read package metadata?
importlib.metadata (Python 3.8+) provides access to installed package metadata — version, entry points, dependencies — without importing the package itself.
from importlib.metadata import version, metadata, entry_points
# Package version
print(version("pip")) # e.g., "24.0"
# Full metadata
meta = metadata("pip")
print(meta["Name"]) # pip
print(meta["Version"])
print(meta["Summary"])
# Entry points
eps = entry_points(group="console_scripts")
for ep in list(eps)[:3]:
print(ep.name, ep.value)
# Map top-level packages to distributions
from importlib.metadata import packages_distributions
dist_map = packages_distributions()
print(dist_map.get("requests")) # ['requests']
Q599: How does __init_subclass__ interact with keyword arguments in class definitions?
Keyword arguments in the class statement (class Foo(Base, key=value)) are forwarded to __init_subclass__. This provides a declarative, metadata-driven configuration mechanism for subclasses.
class Validator:
def __init_subclass__(cls, strict: bool = False, prefix: str = "", **kwargs):
super().__init_subclass__(**kwargs)
cls._strict = strict
cls._prefix = prefix
print(f"Registered {cls.__name__}: strict={strict}, prefix={prefix!r}")
class StrictModel(Validator, strict=True, prefix="model_"):
name: str
age: int
class LaxModel(Validator, strict=False):
data: dict
print(StrictModel._strict) # True
print(StrictModel._prefix) # "model_"
print(LaxModel._strict) # False
Q600: What are Python 3.12 improvements to f-strings and the type statement?
Python 3.12 allows multi-line f-strings, nested quotes inside f-strings without escaping, and introduces the type statement for explicit type aliases. The @override decorator was also added to typing.
# Python 3.12: same quote characters inside f-strings
name = "Alice"
print(f"{'hello'!r}") # works in 3.12+
# type statement (Python 3.12) — explicit type alias
type Vector = list[float]
type Matrix = list[Vector]
# typing.override (Python 3.12) — marks intentional override
from typing import override
class Base:
def process(self) -> str: return "base"
class Child(Base):
@override
def process(self) -> str: return "child" # type checker verifies it overrides a real method
# type aliases are inspectable
print(Vector) # list[float]
print(type(Vector)) # <class 'typing.TypeAliasType'>
Q601: What are __match_args__ and how do they support match/case positional patterns?
__match_args__ specifies the order of attributes for positional pattern matching. Without it, you must use keyword patterns. @dataclass sets __match_args__ automatically from field order.
class Point:
__match_args__ = ("x", "y") # enables positional matching
def __init__(self, x, y):
self.x, self.y = x, y
def classify(point):
match point:
case Point(0, 0): return "Origin"
case Point(0, y): return f"Y-axis at {y}"
case Point(x, 0): return f"X-axis at {x}"
case Point(x, y) if x == y: return f"Diagonal at {x}"
case Point(x, y): return f"Point({x}, {y})"
print(classify(Point(0, 0))) # Origin
print(classify(Point(0, 5))) # Y-axis at 5
print(classify(Point(3, 3))) # Diagonal at 3
# dataclass sets __match_args__ automatically
from dataclasses import dataclass
@dataclass
class Color:
r: int; g: int; b: int
match Color(255, 0, 0):
case Color(255, 0, 0): print("Red")
Q602: How does typing.TypeAlias differ from a plain assignment type alias?
TypeAlias (Python 3.10+) explicitly marks a variable as a type alias, enabling type checkers to distinguish it from regular assignments. The type statement (Python 3.12) makes this even clearer.
from typing import TypeAlias
# Ambiguous — is this a type alias or a runtime value?
Vector = list[float]
# Explicit with TypeAlias (Python 3.10+)
Vector: TypeAlias = list[float]
Matrix: TypeAlias = list[Vector]
# Explicit with type statement (Python 3.12+)
# type Vector = list[float]
def scale(v: Vector, factor: float) -> Vector:
return [x * factor for x in v]
# Generic type alias
from typing import TypeVar
T = TypeVar("T")
Pair: TypeAlias = tuple[T, T]
def swap(pair: Pair) -> Pair:
a, b = pair
return b, a
Q603: What are __slots__ limitations and alternatives for memory optimization?
__slots__ saves memory by replacing __dict__ but has limitations: no dynamic attributes, multiple inheritance requires coordination, and pickling may need __getstate__/__setstate__. For large numbers of objects, consider numpy arrays or the array module.
import sys
from array import array
class NormalPoint:
def __init__(self, x, y):
self.x, self.y = x, y
class SlottedPoint:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x, self.y = x, y
n = NormalPoint(1, 2)
s = SlottedPoint(1, 2)
print(sys.getsizeof(n) + sys.getsizeof(n.__dict__)) # ~280 bytes
print(sys.getsizeof(s)) # ~56 bytes
# For numeric arrays, array module is more memory-efficient than list
points_x = array("f", [1.0, 2.0, 3.0]) # 4 bytes each (float)
points_list = [1.0, 2.0, 3.0] # ~28 bytes each (Python float objects)
Q604: How does asyncio.run_in_executor bridge sync and async code?
loop.run_in_executor(executor, func, *args) runs a blocking function in a thread or process pool without blocking the event loop. Pass None as executor to use the default ThreadPoolExecutor.
import asyncio, time
def blocking_io(n):
"""Simulates a blocking operation (e.g., a legacy sync library)."""
time.sleep(n)
return f"done after {n}s"
def cpu_intensive(n):
return sum(i * i for i in range(n))
async def main():
loop = asyncio.get_running_loop()
# Run blocking I/O in thread pool (default executor)
result = await loop.run_in_executor(None, blocking_io, 0.1)
print(result) # done after 0.1s
# Run CPU-bound work in process pool
from concurrent.futures import ProcessPoolExecutor
with ProcessPoolExecutor() as pool:
result = await loop.run_in_executor(pool, cpu_intensive, 1_000_000)
print(result)
asyncio.run(main())
Q605: What are Python's name mangling rules and when do you use double-underscore prefixes?
Name mangling transforms __name (two leading underscores, at most one trailing) to _ClassName__name at compile time. This prevents accidental overriding in subclasses, not true privacy — mangled names are still accessible if you know the pattern.
class BankAccount:
def __init__(self, balance):
self.__balance = balance # mangled to _BankAccount__balance
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
class CheckingAccount(BankAccount):
def __init__(self, balance, limit):
super().__init__(balance)
self.__balance = limit # mangled to _CheckingAccount__balance — different!
def get_limit(self):
return self.__balance
acct = CheckingAccount(1000, 500)
print(acct.get_balance()) # 1000 — BankAccount.__balance
print(acct.get_limit()) # 500 — CheckingAccount.__balance
print(acct._BankAccount__balance) # 1000 — accessible if you know the name
# Convention summary:
# _name → internal use (by convention, not enforced)
# __name → name-mangled to prevent subclass collision
# __name__ → dunder/magic method — never invent new ones
Q606: API response times spike under load — tracing the bottleneck
Level: Senior
Scenario: A FastAPI e-commerce API averages 120 ms per request normally. During a flash sale, p99 latency jumps to 15 seconds and the service starts returning 504 gateway timeouts. CPU and memory look fine on the instances.
Impact: Users cannot complete checkout. Orders are lost. Revenue drops during peak traffic.
Root Cause: The endpoint calls a downstream inventory service synchronously with requests inside an async def route. Each request blocks the event loop thread. With limited worker threads, all threads become occupied waiting on the slow downstream service, so new requests queue up.
Simple explanation: Think of one cashier who must wait on the phone with a supplier for every customer. While on hold, no other customer can be served. The line grows long.
Fix:
- Replace blocking
requestswithhttpx.AsyncClientso calls are non-blocking. - Add a timeout so one slow downstream call does not hold a worker forever.
- Add circuit breaker so repeated failures fail fast instead of queuing.
- Add retry with exponential backoff for transient downstream failures.
Code/Syntax Justification:
import httpx
from fastapi import FastAPI, HTTPException
app = FastAPI()
client = httpx.AsyncClient(timeout=httpx.Timeout(5.0))
@app.get("/inventory/{sku}")
async def get_inventory(sku: str):
try:
resp = await client.get(f"https://inventory.internal/stock/{sku}")
resp.raise_for_status()
return resp.json()
except httpx.HTTPStatusError as exc:
raise HTTPException(status_code=exc.response.status_code, detail="inventory error")
except httpx.RequestError:
raise HTTPException(status_code=502, detail="inventory service unavailable")
Workflow Diagram:
Client Request
|
v
[FastAPI Route: async def]
|
v
+----> await httpx.get(downstream) ---- non-blocking, event loop free
| |
| response returns |
| or timeout / error |
| v
| [Circuit Breaker]
| / \
| open closed
| | |
| fail fast proceed
| v
| return JSON to client
+----------------------------------------->
|
v
HTTP Response
🔍 Behind the Question: They test whether you know async def does not make blocking I/O non-blocking, and whether you understand timeouts and circuit breakers as resilience patterns.
Red flags: Using requests.get() inside async def; setting no timeout; claiming "async makes everything faster" without addressing blocking calls.
Q607: Memory grows until OOM kill in long-running service
Level: Senior
Scenario: A FastAPI service runs fine after deploy, but RSS memory climbs steadily over 3–4 days until Kubernetes OOM-kills the pod. Restarting temporarily fixes it.
Impact: Periodic outages. Users see 502s when pods restart. On-call gets paged nightly.
Root Cause: A module-level dict cache grows without bound (no TTL or size limit), and some BackgroundTasks capture large request objects that are never released. Python's garbage collector cannot reclaim objects still referenced from module scope.
Simple explanation: It is like a notebook where you keep writing new notes on every page but never tear out old ones. Eventually the notebook is full and you cannot add anything.
Fix:
- Replace unbounded dict cache with
cachetools.TTLCacheor Redis with TTL. - Do not store request objects in module-level variables; pass only needed primitives.
- Add memory profiling (
tracemalloc) and alert on RSS growth trend.
Code/Syntax Justification:
# Before (leaky)
USER_CACHE = {} # grows forever
@app.get("/user/{user_id}")
async def get_user(user_id: int):
if user_id not in USER_CACHE:
USER_CACHE[user_id] = await db.fetch_user(user_id)
return USER_CACHE[user_id]
# After (bounded TTL cache)
from cachetools import TTLCache
USER_CACHE = TTLCache(maxsize=10_000, ttl=300) # 10k entries, 5 min TTL
@app.get("/user/{user_id}")
async def get_user(user_id: int):
if user_id not in USER_CACHE:
USER_CACHE[user_id] = await db.fetch_user(user_id)
return USER_CACHE[user_id]
Workflow Diagram:
Request arrives
|
v
Check USER_CACHE
|
+-- HIT --> return cached value
|
+-- MISS --> fetch from DB
|
v
store in USER_CACHE (with TTL)
|
v
return value
|
v
Background: TTL expires -> entry auto-removed -> memory bounded
🔍 Behind the Question: They test understanding of Python reference cycles, module-level mutable state, and the need for cache eviction policies in long-running services.
Red flags: Saying "Python garbage collector handles it" or "just increase the container memory limit."
Q608: Background task silently fails — email notifications never sent
Level: Senior
Scenario: Users register, but welcome emails are never delivered. The API returns 202 Accepted. No errors appear in application logs.
Impact: New users do not get onboarding emails. Conversion and activation metrics drop.
Root Cause: BackgroundTasks runs after the response is sent, but if the worker process dies or the task raises an exception, there is no retry, no dead-letter queue, and no alerting. The failure is silent.
Simple explanation: You hand a letter to a courier and close the door. If the courier drops it, nobody tells you.
Fix:
- Move critical outbound work (email, billing events) to a durable task queue (Celery / ARQ / RQ) with retry and dead-letter handling, not
BackgroundTasks. - Add structured logging and correlation IDs so failures can be traced.
- Add monitoring/alerting on task failure rate.
Code/Syntax Justification:
# FastAPI endpoint enqueues to Celery
from fastapi import BackgroundTasks, FastAPI
from tasks import send_welcome_email
app = FastAPI()
@app.post("/users/")
async def create_user(user: UserCreate):
db_user = await db.create_user(user)
# Durable, retriable, observable
send_welcome_email.delay(user_id=db_user.id, email=user.email)
return {"id": db_user.id, "status": "created"}
Workflow Diagram:
Client POST /users
|
v
[FastAPI creates user in DB]
|
v
enqueue send_welcome_email task (Celery/RabbitMQ)
|
v
[Worker picks up task]
|
+-- success --> log "sent", mark done
|
+-- failure --> retry with backoff (max N)
|
+-- still failing --> dead-letter queue + alert
|
v
HTTP 202 returned to client (independent of task outcome)
🔍 Behind the Question: They test the difference between fire-and-forget BackgroundTasks (good for non-critical work) and durable task queues (good for business-critical asynchronous work).
Red flags: Using BackgroundTasks for billing/email without retry; no observability on background failures.
Q609: Cascading failure — one slow dependency takes down the whole service
Level: Principal
Scenario: The FastAPI gateway calls three downstream services (payment, inventory, user). The payment service degrades (slow responses). Soon the gateway itself becomes unhealthy, affecting inventory and user calls too, even though those services are fine.
Impact: Total site outage caused by one degraded dependency.
Root Cause: No timeout, no circuit breaker, and no bulkhead isolation. All worker threads/connections get occupied waiting on payment, exhausting the connection pool and leaving no capacity for other calls.
Simple explanation: A narrow hallway gets blocked by one slow person. Everyone behind them is stuck, even people going to different rooms.
Fix:
- Per-dependency timeouts (fail fast).
- Circuit breaker per dependency (open after N failures, reject fast for a cooldown period).
- Bulkhead isolation — separate connection pools / thread pools per downstream service.
- Fallback responses (degraded mode) when a dependency is down.
Code/Syntax Justification:
from circuitbreaker import circuit
import httpx
@circuit(failure_threshold=5, recovery_timeout=30)
async def call_payment(data):
async with httpx.AsyncClient(timeout=3.0) as client:
resp = await client.post("https://payment.internal/charge", json=data)
resp.raise_for_status()
return resp.json()
@app.post("/checkout")
async def checkout(order: Order):
try:
payment = await call_payment(order)
except CircuitBreakerError:
return {"status": "degraded", "message": "payment temporarily unavailable"}
# ... proceed with inventory, user
Workflow Diagram:
Request arrives
|
v
[Timeout set per dependency]
|
v
Call downstream (payment)
|
+-- success within timeout --> proceed
|
+-- timeout / error --> count failure
|
v
[Circuit Breaker]
/ \
closed open
| |
allow call fail fast
| |
v v
continue fallback response
🔍 Behind the Question: They test resilience design: timeouts, circuit breakers, bulkheads, graceful degradation, blast radius. Principal candidates should discuss blast radius and fallback strategies.
Red flags: No timeouts, shared connection pool across all dependencies, retry storms without backoff.
Q610: Race condition — double charging customers on retry
Level: Principal
Scenario: A client retries a POST /payment request after a timeout. The server actually processed the first payment but the response was lost. The retry creates a second charge. Customer is charged twice.
Impact: Financial loss, customer trust damage, refund overhead.
Root Cause: The payment endpoint is not idempotent. There is no idempotency key, so the server treats the retry as a brand-new payment.
Simple explanation: You pay at a cashier, the receipt printer jams, you do not know if it went through, so you pay again. The cashier charges you twice because they do not recognize it is the same purchase.
Fix:
- Require an
Idempotency-Keyheader on write endpoints. - Store processed keys with results in Redis/DB with TTL.
- On retry with same key, return cached result instead of re-processing.
Code/Syntax Justification:
from fastapi import Header, HTTPException
from fastapi.responses import JSONResponse
import redis, json
r = redis.Redis(host="redis", port=6379, db=0)
@app.post("/payment")
async def payment(request: Request, idempotency_key: str = Header(...)):
cache_key = f"idem:{idempotency_key}"
cached = r.get(cache_key)
if cached:
return JSONResponse(content=json.loads(cached), status_code=200)
result = await process_payment(request)
r.setex(cache_key, 86400, json.dumps(result)) # 24h TTL
return result
Workflow Diagram:
Client POST /payment (Idempotency-Key: abc-123)
|
v
[Check Redis for idem:abc-123]
|
+-- FOUND --> return cached result (no re-charge)
|
+-- NOT FOUND --> process payment
|
v
store result in Redis (TTL 24h)
|
v
return result to client
|
v
Client retries with same Idempotency-Key: abc-123
|
v
[Redis HIT] --> return cached result (safe, no double charge)
🔍 Behind the Question: They test idempotency design for distributed systems, exactly-once vs at-least-once delivery, safe retries. Principal candidates discuss exactly-once vs at-least-once delivery and where idempotency keys live.
Red flags: "Just tell clients not to retry"; no idempotency key; storing keys forever without TTL.
Q611: Deploy causes widespread 500s — bad migration or config
Level: Principal
Scenario: After a deploy, all API calls return 500. Rolling back the image fixes it. The change was a new required environment variable and a database column rename.
Impact: Full site outage during deploy window.
Root Cause: The deploy was not backward-compatible. Old code expected the old column; new code expected the new env var. There was no feature flag, no canary, and no rollback validation.
Simple explanation: You swap the engine in a car while it is driving. The car stops because the new parts do not fit the old body yet.
Fix:
- Use backward-compatible database changes (additive columns, dual-write during migration).
- Use feature flags to toggle new behavior per deployment.
- Deploy canary (5% traffic), monitor error rate, then promote.
- Validate config at startup (fail fast if required env vars missing).
Code/Syntax Justification:
# Startup validation
from pydantic import BaseSettings
from fastapi import FastAPI
class Settings(BaseSettings):
DATABASE_URL: str
NEW_FEATURE_FLAG: bool = False
class Config:
env_file = ".env"
settings = Settings()
app = FastAPI()
@app.on_event("startup")
async def validate():
if not settings.DATABASE_URL:
raise RuntimeError("DATABASE_URL is required")
Workflow Diagram:
Deploy new version
|
v
[Startup validation: env vars present?]
|
+-- NO --> fail fast, do not accept traffic
|
+-- YES --> canary rollout (5% traffic)
|
v
[Monitor error rate / latency]
|
+-- healthy --> promote to 100%
|
+-- unhealthy --> auto-rollback to previous version
🔍 Behind the Question: They test zero-downtime deployment, backward compatibility, canary releases, operational maturity.
Red flags: Deploying breaking DB changes without dual-write; no rollback plan; no startup validation.
Part C: Senior / Principal — Real World Scenarios
These questions test production debugging, architecture decisions, and incident response at senior/principal level. Each includes a real-world scenario, impact, root cause, fix, code, and a workflow diagram.
Scenario Q606: API response times spike under load — tracing the bottleneck
Level: Senior
Scenario: A FastAPI e-commerce API averages 120 ms per request normally. During a flash sale, p99 latency jumps to 15 seconds and the service starts returning 504 gateway timeouts. CPU and memory look fine on the instances.
Impact: Users cannot complete checkout. Orders are lost. Revenue drops during peak traffic.
Root Cause: The endpoint calls a downstream inventory service synchronously with requests inside an async def route. Each request blocks the event loop thread. With limited worker threads, all threads become occupied waiting on the slow downstream service, so new requests queue up.
Simple explanation: Think of one cashier who must wait on the phone with a supplier for every customer. While on hold, no other customer can be served. The line grows long.
Fix:
- Replace blocking
requestswithhttpx.AsyncClientso calls are non-blocking. - Add a timeout so one slow downstream call does not hold a worker forever.
- Add circuit breaker so repeated failures fail fast instead of queuing.
- Add retry with exponential backoff for transient downstream failures.
Code:
import httpx
from fastapi import FastAPI, HTTPException
from fastapi.concurrency import asyncio
app = FastAPI()
client = httpx.AsyncClient(timeout=httpx.Timeout(5.0))
@app.get("/inventory/{sku}")
async def get_inventory(sku: str):
try:
resp = await client.get(f"https://inventory.internal/stock/{sku}")
resp.raise_for_status()
return resp.json()
except httpx.HTTPStatusError as exc:
raise HTTPException(status_code=exc.response.status_code, detail="inventory error")
except httpx.RequestError:
raise HTTPException(status_code=502, detail="inventory service unavailable")
Workflow diagram:
Client Request
|
v
[FastAPI Route: async def]
|
v
+----> await httpx.get(downstream) ---- non-blocking, event loop free
| |
| response returns |
| or timeout / error |
| v
| [Circuit Breaker]
| / \
| open closed
| | |
| fail fast proceed
| v
| return JSON to client
+----------------------------------------->
|
v
HTTP Response
Interviewer notes: They test whether you know async def does not make blocking I/O non-blocking, and whether you understand timeouts and circuit breakers as resilience patterns.
Red flags: Using requests.get() inside async def; setting no timeout; claiming "async makes everything faster" without addressing blocking calls.
Scenario Q607: Memory grows until OOM kill in long-running service
Level: Senior
Scenario: A FastAPI service runs fine after deploy, but RSS memory climbs steadily over 3–4 days until Kubernetes OOM-kills the pod. Restarting temporarily fixes it.
Impact: Periodic outages. Users see 502s when pods restart. On-call gets paged nightly.
Root Cause: A module-level dict cache grows without bound (no TTL or size limit), and some BackgroundTasks capture large request objects that are never released. Python's garbage collector cannot reclaim objects still referenced from module scope.
Simple explanation: It is like a notebook where you keep writing new notes on every page but never tear out old ones. Eventually the notebook is full and you cannot add anything.
Fix:
- Replace unbounded dict cache with
cachetools.TTLCacheor Redis with TTL. - Do not store request objects in module-level variables; pass only needed primitives.
- Add memory profiling (
tracemalloc) and alert on RSS growth trend.
Code:
# Before (leaky)
USER_CACHE = {} # grows forever
@app.get("/user/{user_id}")
async def get_user(user_id: int):
if user_id not in USER_CACHE:
USER_CACHE[user_id] = await db.fetch_user(user_id)
return USER_CACHE[user_id]
# After (bounded TTL cache)
from cachetools import TTLCache
USER_CACHE = TTLCache(maxsize=10_000, ttl=300) # 10k entries, 5 min TTL
@app.get("/user/{user_id}")
async def get_user(user_id: int):
if user_id not in USER_CACHE:
USER_CACHE[user_id] = await db.fetch_user(user_id)
return USER_CACHE[user_id]
Workflow diagram:
Request arrives
|
v
Check USER_CACHE
|
+-- HIT --> return cached value
|
+-- MISS --> fetch from DB
|
v
store in USER_CACHE (with TTL)
|
v
return value
|
v
Background: TTL expires -> entry auto-removed -> memory bounded
Interviewer notes: They test understanding of Python reference cycles, module-level mutable state, and the need for cache eviction policies in long-running services.
Red flags: Saying "Python garbage collector handles it" or "just increase the container memory limit."
Scenario Q608: Background task silently fails — email notifications never sent
Level: Senior
Scenario: Users register, but welcome emails are never delivered. The API returns 202 Accepted. No errors appear in application logs.
Impact: New users do not get onboarding emails. Conversion and activation metrics drop.
Root Cause: BackgroundTasks runs after the response is sent, but if the worker process dies or the task raises an exception, there is no retry, no dead-letter queue, and no alerting. The failure is silent.
Simple explanation: You hand a letter to a courier and close the door. If the courier drops it, nobody tells you.
Fix:
- Move critical outbound work (email, billing events) to a durable task queue (Celery / ARQ / RQ) with retry and dead-letter handling, not
BackgroundTasks. - Add structured logging and correlation IDs so failures can be traced.
- Add monitoring/alerting on task failure rate.
Code:
# FastAPI endpoint enqueues to Celery
from fastapi import BackgroundTasks, FastAPI
from tasks import send_welcome_email
app = FastAPI()
@app.post("/users/")
async def create_user(user: UserCreate):
db_user = await db.create_user(user)
# Durable, retriable, observable
send_welcome_email.delay(user_id=db_user.id, email=user.email)
return {"id": db_user.id, "status": "created"}
Workflow diagram:
Client POST /users
|
v
[FastAPI creates user in DB]
|
v
enqueue send_welcome_email task (Celery/RabbitMQ)
|
v
[Worker picks up task]
|
+-- success --> log "sent", mark done
|
+-- failure --> retry with backoff (max N)
|
+-- still failing --> dead-letter queue + alert
|
v
HTTP 202 returned to client (independent of task outcome)
Interviewer notes: They test the difference between fire-and-forget BackgroundTasks (good for non-critical work) and durable task queues (good for business-critical asynchronous work).
Red flags: Using BackgroundTasks for billing/email without retry; no observability on background failures.
Scenario Q609: Cascading failure — one slow dependency takes down the whole service
Level: Principal
Scenario: The FastAPI gateway calls three downstream services (payment, inventory, user). The payment service degrades (slow responses). Soon the gateway itself becomes unhealthy, affecting inventory and user calls too, even though those services are fine.
Impact: Total site outage caused by one degraded dependency.
Root Cause: No timeout, no circuit breaker, and no bulkhead isolation. All worker threads/connections get occupied waiting on payment, exhausting the connection pool and leaving no capacity for other calls.
Simple explanation: A narrow hallway gets blocked by one slow person. Everyone behind them is stuck, even people going to different rooms.
Fix:
- Per-dependency timeouts (fail fast).
- Circuit breaker per dependency (open after N failures, reject fast).
- Bulkhead isolation — separate connection pools / thread pools per downstream service.
- Fallback responses (degraded mode) when a dependency is down.
Code:
from circuitbreaker import circuit
import httpx
@circuit(failure_threshold=5, recovery_timeout=30)
async def call_payment(data):
async with httpx.AsyncClient(timeout=3.0) as client:
resp = await client.post("https://payment.internal/charge", json=data)
resp.raise_for_status()
return resp.json()
@app.post("/checkout")
async def checkout(order: Order):
try:
payment = await call_payment(order)
except CircuitBreakerError:
return {"status": "degraded", "message": "payment temporarily unavailable, order queued"}
# ... proceed with inventory, user
Workflow diagram:
Request arrives
|
v
[Timeout set per dependency]
|
v
Call downstream (payment)
|
+-- success within timeout --> proceed
|
+-- timeout / error --> count failure
|
v
[Circuit Breaker]
/ \
closed open
| |
allow call fail fast
| |
v v
continue fallback response
Interviewer notes: They test resilience design: timeouts, circuit breakers, bulkheads, and graceful degradation. Principal candidates should discuss blast radius and fallback strategies.
Red flags: No timeouts, shared connection pool across all dependencies, retry storms without backoff.
Scenario Q610: Race condition — double charging customers on retry
Level: Principal
Scenario: A client retries a POST /payment request after a timeout. The server actually processed the first payment but the response was lost. The retry creates a second charge. Customer is charged twice.
Impact: Financial loss, customer trust damage, refund overhead.
Root Cause: The payment endpoint is not idempotent. There is no idempotency key, so the server treats the retry as a brand-new payment.
Simple explanation: You pay at a cashier, the receipt printer jams, you don't know if it went through, so you pay again. The cashier charges you twice because they do not recognize it is the same purchase.
Fix:
- Require an
Idempotency-Keyheader on write endpoints. - Store processed keys with results in Redis/DB with TTL.
- On retry with same key, return cached result instead of re-processing.
Code:
from fastapi import Request, Header, HTTPException
import redis
r = redis.Redis(host="redis", port=6379, db=0)
@app.post("/payment")
async def payment(request: Request, idempotency_key: str = Header(...)):
cache_key = f"idem:{idempotency_key}"
cached = r.get(cache_key)
if cached:
return JSONResponse(content=json.loads(cached), status_code=200)
result = await process_payment(request) # actual charge
r.setex(cache_key, 86400, json.dumps(result)) # 24h TTL
return result
Workflow diagram:
Client POST /payment (Idempotency-Key: abc-123)
|
v
[Check Redis for idem:abc-123]
|
+-- FOUND --> return cached result (no re-charge)
|
+-- NOT FOUND --> process payment
|
v
store result in Redis (TTL 24h)
|
v
return result to client
|
v
Client retries with same Idempotency-Key: abc-123
|
v
[Redis HIT] --> return cached result (safe, no double charge)
Interviewer notes: They test idempotency design for distributed systems, exactly-once semantics, and safe retries. Principal candidates discuss exactly-once vs at-least-once delivery and where idempotency keys live.
Red flags: "Just tell clients not to retry"; no idempotency key; storing keys forever without TTL.
Scenario Q611: Deploy causes widespread 500s — bad migration or config
Level: Principal
Scenario: After a deploy, all API calls return 500. Rolling back the image fixes it. The change was a new required environment variable and a database column rename.
Impact: Full site outage during deploy window.
Root Cause: The deploy was not backward-compatible. Old code expected the old column; new code expected the new env var. There was no feature flag, no canary, and no rollback validation.
Simple explanation: You swap the engine in a car while it is driving. The car stops because the new parts do not fit the old body yet.
Fix:
- Use backward-compatible database changes (additive columns, dual-write during migration).
- Use feature flags to toggle new behavior per deployment.
- Deploy canary (5% traffic), monitor error rate, then promote.
- Validate config at startup (fail fast if required env vars missing).
Code:
# Startup validation
from pydantic import BaseSettings
from fastapi import FastAPI
class Settings(BaseSettings):
DATABASE_URL: str
NEW_FEATURE_FLAG: bool = False # default off
class Config:
env_file = ".env"
settings = Settings()
app = FastAPI()
@app.on_event("startup")
async def validate():
if not settings.DATABASE_URL:
raise RuntimeError("DATABASE_URL is required")
Workflow diagram:
Deploy new version
|
v
[Startup validation: env vars present?]
|
+-- NO --> fail fast, do not accept traffic
|
+-- YES --> canary rollout (5% traffic)
|
v
[Monitor error rate / latency]
|
+-- healthy --> promote to 100%
|
+-- unhealthy --> auto-rollback to previous version
Interviewer notes: They test zero-downtime deployment, backward compatibility, canary releases, and operational maturity.
Red flags: Deploying breaking DB changes without dual-write; no rollback plan; no startup validation.