Skip to content
tezvyn:

Top 30 Advanced Python & FastAPI Concepts Quiz

30 advanced multiple-choice Python & FastAPI concept questions, the corners that separate having used it from understanding it: internals, edge cases, and the reasons behind the design. They come from 30 bites in the Python & FastAPI library, the hardest slice of the 109 Python & FastAPI concept questions in the library. Answer them here or read straight down. Every question carries the correct option, why it is correct, and a link to the bite it came from.

Python, Django, FastAPI, Flask, async Python

30 questions. Pick an answer, or open “Show the answer” to read it.

Answers are graded in your browser. Nothing is saved, and no XP or streak is earned here. The app keeps score.

  1. Question 1 of 30

    You write an async generator that awaits during resource teardown, but mistakenly decorate it with @contextmanager. What is the most likely result?

    Show the answer

    Answer: b · A runtime error occurs because the synchronous decorator cannot await inside the generator

    The card explicitly warns that @contextmanager is for synchronous generators only and cannot await, causing a crash. Distractor A is tempting because blocking the event loop is discussed as a general risk of async code, but the specific mistake of using the sync decorator with async cleanup results in a runtime error rather than silent blocking.

    Read the full bite: Python Async Context Managers

  2. Question 2 of 30

    What specific problem did direct access to "__annotations__" for a class, like "Derived.__annotations__", commonly cause in Python 3.9 that "inspect.get_annotations()" addresses in Python 3.10+?

    Show the answer

    Answer: c · It would incorrectly show annotations inherited from a parent class, even if the derived class had no explicit annotations.

    In Python 3.9 and earlier, direct access to a class's __annotations__ would incorrectly include annotations inherited from parent classes. Python 3.10+ and `inspect.get_annotations()` resolve this by ensuring a class's __annotations__ only contains its own explicitly defined annotations, returning an empty dictionary if none are present.

    Read the full bite: Accessing Python Type Annotations Safely

  3. Question 3 of 30

    Why is Python's threading module generally not recommended for speeding up CPU-bound tasks on multi-core machines?

    Show the answer

    Answer: a · The Global Interpreter Lock (GIL) prevents multiple threads from executing Python bytecode simultaneously.

    The card states that the GIL "prevents multiple threads from executing Python code at the same time," which is the fundamental reason threading cannot achieve true parallelism for CPU-bound tasks. While thread management overhead (option C) can make a program slower, the GIL is the core reason it won't speed up by utilizing multiple CPU cores.

    Read the full bite: Python Concurrency vs. Parallelism

  4. Question 4 of 30

    What is the primary reason Python's threading module can improve performance for I/O-bound applications despite the Global Interpreter Lock (GIL)?

    Show the answer

    Answer: d · The GIL is released by a thread when it enters a waiting state for an I/O operation, allowing other threads to execute Python bytecode.

    The card explains that when a thread is blocked waiting for an I/O operation, the GIL is released, allowing other threads to acquire it and execute Python bytecode, thereby improving concurrency. Option C is incorrect because the GIL is released and reacquired, not entirely bypassed.

    Read the full bite: The Python GIL: One Thread at a Time

  5. Question 5 of 30

    In a FastAPI application, when is it appropriate to explicitly raise HTTPException?

    Show the answer

    Answer: b · To signal that a requested resource or business rule violation occurred due to client input.

    HTTPException is designed for expected, client-caused errors like a missing resource (404) or a permission issue (403), which stem from business logic. FastAPI automatically handles Pydantic validation errors (422) and it's not for unexpected server bugs (500).

    Read the full bite: FastAPI: Use HTTPException to Return Client Errors

  6. Question 6 of 30

    A developer implements a CPU-intensive image resize inside an async def FastAPI endpoint. Under concurrent load, what is the most likely outcome?

    Show the answer

    Answer: b · The event loop blocks during each resize, starving other concurrent requests

    CPU-intensive work inside async def never yields control to the event loop, so it starves other requests on the same worker. FastAPI only runs regular def routes in a thread pool, and async does not create parallel multicore execution.

    Read the full bite: Async Path Operations in FastAPI

  7. Question 7 of 30

    Which statement accurately describes a key behavior when consuming the request body via Starlette's Request object?

    Show the answer

    Answer: c · It must be explicitly awaited, and the underlying stream can only be read once.

    The card explicitly states that accessing the body involves 'await-ing methods that consume the receive channel' and that 'This body consumption can only happen once.' Option A is a common misconception, as the Request object treats the body as a stream that is consumed upon the first read, not automatically cached.

    Read the full bite: Starlette's Request Object: A Clean API for ASGI

  8. Question 8 of 30

    What is the primary purpose of using a Pydantic @computed_field?

    Show the answer

    Answer: b · To automatically include a value derived from other fields in the model's serialized output.

    A computed field promotes a derived value to be part of the model's exportable data, automatically including it in the serialized output. It is not for defining fundamental inputs, which should be regular Pydantic fields.

    Read the full bite: Pydantic Computed Fields: Serialize Derived Values

  9. Question 9 of 30

    What is the primary reason to use a `yield` dependency instead of a standard `return` dependency in FastAPI?

    Show the answer

    Answer: d · To allow for resource cleanup operations to execute after the endpoint's logic.

    Yield dependencies are specifically designed for 'setup and teardown' scenarios, enabling cleanup code to run after the endpoint has finished processing. The code after `yield` executes after the response has been sent, so it cannot modify the HTTP response.

    Read the full bite: FastAPI `yield` Dependencies for Setup and Teardown

  10. Question 10 of 30

    In FastAPI, when you need to add a custom HTTP header like a trace ID to a JSON response without altering the response body, what is the correct method?

    Show the answer

    Answer: b · Declare a Response parameter in the path operation, set headers on its .headers attribute, and return your data normally.

    The card states to declare a Response parameter, set headers on its .headers attribute, and then return your data normally. Returning the Response object directly (option A) is explicitly warned against as a 'footgun' because FastAPI automatically merges the headers with your returned data.

    Read the full bite: FastAPI: Setting Custom Response Headers

  11. Question 11 of 30

    What is the primary reason to use FastAPI's Security() utility instead of Depends() for authentication?

    Show the answer

    Answer: a · It signals to OpenAPI that a dependency is a security requirement, enabling interactive documentation.

    The card emphasizes that the key distinction of Security() is its role in signaling security requirements to OpenAPI, which enables interactive documentation features like lock icons and 'Authorize' buttons. While Security() does work with functions that raise HTTPExceptions for authentication failures, standard Depends() can also be used with such functions, making the OpenAPI integration the primary differentiator.

    Read the full bite: FastAPI's Security Utility: Dependencies for Auth

  12. Question 12 of 30

    Which scenario is generally discouraged when applying FastAPI dependency overriding?

    Show the answer

    Answer: a · Substituting a pure function that performs calculations without side effects.

    The card explicitly advises against overriding simple, pure-function dependencies that have no side effects, as it introduces unnecessary complexity. The other options describe recommended use cases for isolating tests from external services, databases, or complex logic.

    Read the full bite: Overriding FastAPI Dependencies for Testing

  13. Question 13 of 30

    For which task would a developer most appropriately access the raw Request object in a FastAPI endpoint?

    Show the answer

    Answer: d · Retrieving the client's IP address for logging purposes.

    The card explicitly states that retrieving the client's IP address is a common and appropriate use case for accessing the raw Request object. Using the raw Request object for standard tasks like extracting query parameters or validating Pydantic models bypasses FastAPI's declarative syntax, validation, and documentation features, which is advised against.

    Read the full bite: Accessing the Raw Request Object in FastAPI

  14. Question 14 of 30

    When developing a FastAPI application, which scenario would make app.mount() an inappropriate choice?

    Show the answer

    Answer: c · Ensuring all sub-components consistently apply a shared dependency injection pattern and global middleware.

    The card explicitly states, "Don't use mounting if you need to share dependencies, middleware, or configuration between application components." Mounting isolates sub-applications, preventing them from inheriting the main app's shared concerns.

    Read the full bite: FastAPI: Mounting Independent Sub-Applications

  15. Question 15 of 30

    For which scenario is an async generator the most suitable Python construct?

    Show the answer

    Answer: c · Generating a sequence of values where each value's creation involves an I/O operation that must be awaited.

    The card states async generators are ideal "when you need to produce a sequence of items, and the production of each item involves an I/O-bound operation that needs to be awaited." Option A is incorrect because async generators do not support returning a final value after yielding, and C describes a regular generator's use case.

    Read the full bite: Async Generators: `yield` in an `async` World

  16. Question 16 of 30

    When is it appropriate for a developer to directly implement asyncio Transports and Protocols?

    Show the answer

    Answer: a · When building a new networking library for a custom byte-stream protocol.

    The card explicitly states that Transports and Protocols should be used "Only when building a networking library or framework from the ground up" for custom protocols. For common tasks like HTTP clients or basic TCP servers, higher-level APIs are recommended, as direct use is considered a "common footgun" for application code.

    Read the full bite: asyncio: Transports Move Bytes, Protocols Decide Which Bytes

  17. Question 17 of 30

    Which of the following best describes the primary historical use case that led to the creation and adoption of custom asyncio event loop policies?

    Show the answer

    Answer: c · To globally substitute the default event loop implementation with a custom or higher-performance alternative.

    The card explicitly states that a primary use case for custom policies was "to globally install a different event loop implementation, such as uvloop, for a performance boost." Option A is a function of how policies manage loops, but the *custom* policy's main historical motivation was changing the *type* of loop.

    Read the full bite: asyncio Event Loop Policies: A Deprecated Pattern

  18. Question 18 of 30

    Which scenario best justifies using loop.run_in_executor() in an asyncio application?

    Show the answer

    Answer: c · To prevent a CPU-bound, synchronous task from stalling the event loop.

    loop.run_in_executor() is designed to offload CPU-intensive, synchronous (blocking) tasks to a separate thread pool, preventing them from blocking the single-threaded event loop. Using it for an already awaitable function would add unnecessary overhead, not improve performance.

    Read the full bite: Debugging Python's Asyncio

  19. Question 19 of 30

    When querying a "to-many" relationship in SQLAlchemy, under which condition is selectinload() generally preferred over joinedload()?

    Show the answer

    Answer: c · When the "to-many" collection is potentially large, to avoid performance issues from a Cartesian product.

    selectinload() is preferred for large "to-many" relationships because joinedload() uses a SQL JOIN, which can create a Cartesian product, leading to excessive data transfer. selectinload() avoids this by issuing a separate SELECT query for the related objects, making it more efficient in such scenarios.

    Read the full bite: SQLAlchemy: Control When Your Relationships Load

  20. Question 20 of 30

    Which scenario best describes the primary use case for OpenID Connect (OIDC) compared to plain OAuth 2.0?

    Show the answer

    Answer: a · An application needs to verify a user's identity and establish a session without handling their credentials.

    OIDC's core purpose is to provide authentication, allowing an application to verify a user's identity and establish a session without the application ever handling the user's password. Option D describes the use case for plain OAuth 2.0, which is for authorization (granting access to resources) rather than identity verification for login.

    Read the full bite: OpenID Connect (OIDC): Authentication as a Service

  21. Question 21 of 30

    Which scenario best highlights the primary benefit of using Double Submit Cookies for CSRF protection?

    Show the answer

    Answer: b · For a Single Page Application (SPA) interacting with a stateless REST API.

    The card states Double Submit Cookies are "ideal for stateless applications" like SPAs with REST/GraphQL APIs, specifically because they avoid "maintaining session state on the server just for CSRF tokens." Option A is incorrect because the card explicitly mentions DSC's main weakness is its vulnerability to XSS.

    Read the full bite: CSRF: Double Submit Cookies for Stateless Backends

  22. Question 22 of 30

    For which scenario is Celery the most suitable solution in a FastAPI application?

    Show the answer

    Answer: a · Executing a long-running, resource-intensive task, such as video transcoding, without blocking the main web server.

    Celery is designed to offload slow, long-running tasks like video transcoding to separate worker processes, preventing the main web server from being blocked and ensuring API responsiveness. Option D describes a use case better suited for FastAPI's built-in BackgroundTasks, which are for lighter, in-process background operations.

    Read the full bite: Celery: Offloading Work from Your FastAPI App

  23. Question 23 of 30

    Which scenario best illustrates the primary purpose of Pytest's monkeypatch fixture?

    Show the answer

    Answer: d · Simulating responses from external dependencies like network APIs or filesystem operations to ensure test isolation.

    The card emphasizes that monkeypatch is for isolating tests from external boundaries like network calls or filesystem access by providing predictable fakes. While monkeypatch can modify global settings or internal functions, its changes are temporary per test, and for internal components, dependency injection is often preferred to avoid brittleness.

    Read the full bite: Mocking with Pytest's monkeypatch

  24. Question 24 of 30

    What is the primary purpose of using `client.websocket_connect` in FastAPI tests?

    Show the answer

    Answer: b · To simulate a complete, interactive client-server conversation with a WebSocket endpoint.

    The card emphasizes that `websocket_connect` is for testing interactive, stateful protocols by simulating a live client connection over its entire lifecycle, including sending and receiving multiple messages sequentially. Option D is incorrect because it describes a single, non-interactive exchange, which misses the core 'conversation' aspect of WebSocket testing.

    Read the full bite: Testing WebSockets in FastAPI

  25. Question 25 of 30

    You override app.openapi to filter paths and add vendor extensions. What step is essential to prevent performance degradation in production?

    Show the answer

    Answer: d · Cache the modified dictionary on the app instance so the function returns the same object on subsequent calls

    The card warns that forgetting to cache the result forces FastAPI to rebuild the schema on every docs request, destroying performance. Caching the modified dict on the app instance ensures subsequent calls return the same object without recomputing, whereas a startup handler does not prevent repeated hook invocations.

    Read the full bite: Overriding FastAPI's OpenAPI Generator

  26. Question 26 of 30

    When customizing FastAPI's Swagger UI, why must configuration keys like "docExpansion" be in camelCase?

    Show the answer

    Answer: c · These keys are directly consumed by the underlying JavaScript Swagger UI library.

    The card states that "keys are camelCase strings, which is how the JavaScript library expects them, not Python's snake_case." This indicates the dictionary is a direct passthrough to the frontend JavaScript. Distractor A is incorrect because the card explicitly mentions that snake_case keys would be "silently ignored," meaning no automatic conversion occurs.

    Read the full bite: Customizing FastAPI's Swagger UI Behavior

  27. Question 27 of 30

    When deploying a FastAPI application behind a reverse proxy, what problem does configuring root_path primarily solve?

    Show the answer

    Answer: a · To inform FastAPI about the public URL prefix that the proxy might remove, ensuring all generated URLs are accurate.

    FastAPI's root_path parameter is used to tell the application about the public-facing URL prefix that a reverse proxy might strip before forwarding requests. This ensures that FastAPI generates correct URLs for clients, particularly for OpenAPI documentation and 'Try it out' features. Other options describe functions of a reverse proxy itself, not what root_path configures within FastAPI.

    Read the full bite: FastAPI Behind a Reverse Proxy: Fixing Docs URLs

  28. Question 28 of 30

    In FastAPI's WebSocket state machine, what is the primary role of await websocket.accept()?

    Show the answer

    Answer: d · To transition the server's application_state from CONNECTING to CONNECTED, allowing send and receive operations.

    The primary role of websocket.accept() is to explicitly update the server's internal application_state to CONNECTED, which is a mandatory step before the server can send or receive messages. While it does send an acceptance message to the client, its fundamental purpose is not to send initial data but to enable subsequent communication by managing the server's state.

    Read the full bite: FastAPI's WebSocket State Machine

  29. Question 29 of 30

    Which characteristic of an ASGI application would make it LEAST suitable for deployment using Mangum on a serverless platform?

    Show the answer

    Answer: b · It requires persistent in-memory state to be maintained between successive requests.

    The card explicitly states that Mangum should be avoided if an application relies on "in-memory state that must persist between requests," as this conflicts with the ephemeral nature of serverless functions. The other options describe scenarios that are well-suited for Mangum and serverless deployment.

    Read the full bite: Mangum: Run Python ASGI Apps on Serverless

  30. Question 30 of 30

    When deploying FastAPI in containers behind a load balancer, why is it recommended to run a single Uvicorn process per container rather than multiple workers per container?

    Show the answer

    Answer: a · It keeps signal handling clean, minimizes failure domains, and lets the orchestrator handle horizontal scaling by adding containers.

    The card emphasizes that one process per container keeps signal handling clean and failure domains small while letting the orchestrator handle replication. Distractor D misapplies immutability; the image is already immutable at build time regardless of how many processes run inside.

    Read the full bite: FastAPI Container Build and Deploy Pipeline

Could you explain these out loud?

That is what an interview actually tests. Tezvyn gives you questions like these with what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon