Skip to content
tezvyn:

Top 30 Python & FastAPI Concepts Quiz

30 multiple-choice questions on the Python & FastAPI fundamentals, drawn from 30 bites in the Python & FastAPI 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

    What is the primary mechanism by which Python type hints improve code reliability?

    Show the answer

    Answer: c · They enable static analysis tools to identify potential type mismatches before execution.

    Type hints are ignored by the Python interpreter at runtime. Their primary role is to allow static analysis tools to check for type consistency and potential errors before the code is ever executed, improving reliability. They do not perform runtime validation of external data.

    Read the full bite: Python Type Hints: Documentation Your Linter Can Read

  2. Question 2 of 30

    For which scenario would a Python dataclass be the most suitable choice?

    Show the answer

    Answer: d · Creating a simple data structure to represent an API response with predefined fields.

    Dataclasses are designed for classes whose primary purpose is to store and group data, making them perfect for structured records like API responses. They are not recommended for classes with complex logic, intricate state, or custom initialization needs, which are better handled by regular classes.

    Read the full bite: Python Data Classes: Write Less Boilerplate

  3. Question 3 of 30

    What is the primary function of an __init__.py file in a Python directory?

    Show the answer

    Answer: c · To explicitly designate the directory as a Python package.

    The card states that "Its mere presence turns a regular directory into an importable package," indicating its fundamental role is to mark a directory as a package. While it can contain code to import sub-modules (option A), this is an optional setup task, not its primary function of defining the package itself.

    Read the full bite: Python Packages: Grouping Modules with __init__.py

  4. Question 4 of 30

    What primary problem do Python Enums address in code?

    Show the answer

    Answer: c · Making code more readable and less prone to errors when using fixed sets of values.

    The card states Enums solve the problem of "magic values" by providing a "robust, readable, and type-safe way to define a fixed set of named constants," making code's intent "immediately clear." While Enums contribute to type safety, their primary purpose is to replace obscure "magic numbers" with meaningful names for fixed sets of choices, improving readability and reducing errors from typos or misunderstandings.

    Read the full bite: Python Enums: Give Names to Magic Numbers

  5. Question 5 of 30

    When a decorator is applied to a function, what is the immediate effect on that function's definition?

    Show the answer

    Answer: d · It replaces the original function in its scope with a new, wrapped function.

    The card states that the decorator returns a wrapper function, which 'replaces the original my_func in the surrounding scope.' This means the original function's name now refers to the new, wrapped function. Option A is incorrect because decorators add behavior without altering the original function's source code.

    Read the full bite: Python Decorators: Functions that Wrap Functions

  6. Question 6 of 30

    What is the primary benefit of using `yield` in a Python function?

    Show the answer

    Answer: a · It enables the function to pause and resume execution, producing values on-demand to conserve memory.

    The card states generators process data lazily, yielding one item at a time to conserve memory by pausing and resuming execution. Option D is incorrect because generators are one-time-use iterators.

    Read the full bite: Python's `yield`: Functions That Pause and Resume

  7. Question 7 of 30

    What is the primary advantage of using a `with` statement in Python for resource management?

    Show the answer

    Answer: d · It ensures that acquired resources are reliably released, regardless of execution flow or errors.

    The `with` statement's core benefit is guaranteeing that resources like file handles or network connections are properly closed or released, even if exceptions interrupt the program flow. While it interacts with errors, it doesn't automatically handle all exceptions; rather, it ensures cleanup *despite* them.

    Read the full bite: The `with` Statement: Python's Automatic Cleanup Crew

  8. Question 8 of 30

    What is the immediate result of calling a function defined with async def, like my_coro(), without awaiting it?

    Show the answer

    Answer: c · A coroutine object is returned, which must be explicitly run by an event loop.

    Calling an async def function directly only creates a coroutine object; it does not execute the function's code. This object must then be awaited or scheduled with an event loop to run. Option B describes synchronous function behavior, and Option A incorrectly implies immediate background execution without the necessary explicit step.

    Read the full bite: Python Coroutines: Functions You Can Pause and Resume

  9. Question 9 of 30

    For which scenario would Python's async/await typically NOT provide a performance benefit?

    Show the answer

    Answer: b · Processing a large dataset with intensive numerical calculations.

    Async/await is designed for I/O-bound tasks where the program spends time waiting, allowing other tasks to run during these waits. CPU-bound tasks, like intensive numerical calculations, will block the single event loop, preventing any other tasks from progressing and thus negating the benefits of concurrency.

    Read the full bite: Python's async/await: Concurrent, Not Parallel

  10. Question 10 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

  11. Question 11 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

  12. Question 12 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

  13. Question 13 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

  14. Question 14 of 30

    What is the primary reason for creating a single FastAPI instance (e.g., app = FastAPI()) for your application?

    Show the answer

    Answer: d · It serves as the central manager for all routing, configuration, and lifecycle events.

    The FastAPI instance acts as the central, authoritative object that orchestrates the entire application, managing all routing, configuration, and lifecycle events. While it does contribute to API documentation, that is a feature derived from its central management role, not its primary purpose for being a single instance.

    Read the full bite: FastAPI Application Instance: Your API's Central Hub

  15. Question 15 of 30

    Which scenario represents an inappropriate use of a FastAPI path operation decorator's arguments?

    Show the answer

    Answer: c · Dynamically changing the HTTP status code based on specific input conditions.

    FastAPI decorator arguments are designed for static configuration, such as setting a default status code or grouping endpoints. Dynamic logic, like returning different status codes based on request input, should be handled within the endpoint function itself, not via decorator arguments.

    Read the full bite: FastAPI: Configure Endpoints with Decorators

  16. Question 16 of 30

    In FastAPI, what is the primary consequence of defining a path parameter without a type hint (e.g., item_id instead of item_id: int)?

    Show the answer

    Answer: c · The path parameter will always be treated as a string, regardless of its content.

    The card explicitly states that 'without int, 123 is just a string,' meaning FastAPI treats untyped path parameters as strings by default. FastAPI does not infer types for path parameters; it requires explicit type hints for validation and conversion.

    Read the full bite: Path Parameters: Turning URL Parts into Variables

  17. Question 17 of 30

    For which purpose are FastAPI query parameters most appropriately used?

    Show the answer

    Answer: b · To provide optional criteria for filtering or paginating a list of items.

    The card states query parameters are for optional data like filtering, pagination, or sorting a collection of resources. Options A and D describe the purpose of path parameters, while option A describes when to use a request body, not query parameters.

    Read the full bite: FastAPI Query Parameters: Beyond the URL Path

  18. Question 18 of 30

    What is the primary benefit of using Uvicorn workers for a FastAPI application in production?

    Show the answer

    Answer: d · It allows the application to utilize multiple CPU cores for concurrent request processing.

    Uvicorn workers are designed to scale your application by running multiple processes, each capable of handling requests, thereby utilizing all available CPU cores to process requests concurrently. Options A and B are incorrect because workers actually complicate debugging and disable auto-reloading; option A is wrong as workers do not fix fundamentally slow or blocking application logic.

    Read the full bite: Uvicorn Workers: Scaling Your FastAPI App

  19. Question 19 of 30

    When developing a FastAPI application, for which purpose is a Pydantic BaseModel most effectively utilized?

    Show the answer

    Answer: d · To define the expected structure and types of data within a POST or PUT request's body.

    The card states that Pydantic models are used for 'the request body of any POST, PUT, or PATCH endpoint where the client sends structured data.' Options A, B, and D describe scenarios where Pydantic models are explicitly advised not to be used for the primary request body model, as those are handled by other FastAPI mechanisms like path parameters, query parameters, or Form().

    Read the full bite: FastAPI: Pydantic for Robust Request Bodies

  20. Question 20 of 30

    When an internal object has fields not defined in a FastAPI response_model, what is the primary action FastAPI takes?

    Show the answer

    Answer: b · It automatically filters out those extra fields before sending the response.

    The `response_model` acts as a stencil, automatically filtering out any fields from the internal object that are not defined in the model before sending the response. It does not raise an error for extra fields, nor does it require manual exclusion for this purpose.

    Read the full bite: FastAPI Response Models: Shape Your API's Output

  21. Question 21 of 30

    What is the fundamental principle behind FastAPI's ability to provide accurate and up-to-date API documentation?

    Show the answer

    Answer: d · It automatically generates documentation by introspecting the application's Python code and type hints.

    The card states, "Think of your code as the single source of truth for your documentation. FastAPI reads your Python functions, their parameters, their type hints..." This means the documentation is generated directly from the code, ensuring it's always current. Other options describe alternative or supplementary methods, but not FastAPI's core mechanism for documentation generation.

    Read the full bite: FastAPI: Automatic Interactive API Docs

  22. Question 22 of 30

    When a parameter validated by FastAPI's Query or Path objects fails its defined constraints, what is the immediate outcome?

    Show the answer

    Answer: b · FastAPI stops request processing and returns a 422 Unprocessable Entity error to the client.

    The card states that if validation fails, FastAPI immediately stops processing and returns a 422 Unprocessable Entity error. This prevents invalid data from reaching your function and provides clear feedback to the client, unlike the other options which describe different error handling or value manipulation.

    Read the full bite: FastAPI: Validate Parameters with Query and Path

  23. Question 23 of 30

    Which is the correct way to set a 201 Created status for a new resource created via a FastAPI POST endpoint?

    Show the answer

    Answer: c · @app.post("/items/", status_code=201)

    The card explicitly states that the success status code should be set in the path operation decorator, as shown in option C, because it's part of the endpoint's contract. Option A is identified as a 'common footgun' for placing it in the function signature, and option D incorrectly uses HTTPException for a success code.

    Read the full bite: FastAPI: Set a Response's HTTP Status Code

  24. Question 24 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

  25. Question 25 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

  26. Question 26 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

  27. Question 27 of 30

    To define a Pydantic model field named "notes" that can be entirely absent from input data without causing a validation error, which definition should be used?

    Show the answer

    Answer: b · notes: str | None = None

    The definition "notes: str | None = None" correctly makes the field optional because it provides a default value of None. If the field is missing from the input, Pydantic will use None without raising an error. Option C, "notes: str | None", only indicates that None is an acceptable value if the field is provided, but without a default, the field is still considered required if entirely absent from the input data.

    Read the full bite: Pydantic: Required vs. Optional Fields

  28. Question 28 of 30

    For which scenario are nested Pydantic models most appropriate?

    Show the answer

    Answer: c · To accurately represent and validate hierarchical data, such as JSON with nested objects.

    Nested Pydantic models are specifically designed to handle and validate complex, hierarchical data structures like JSON objects containing other objects. Using them for flat data is explicitly advised against, as it adds unnecessary complexity.

    Read the full bite: Nested Pydantic Models: Composing Complex Data

  29. Question 29 of 30

    When would a developer choose to disable Pydantic's default data coercion for a field?

    Show the answer

    Answer: c · To enforce that the input data's type precisely matches the annotated Python type, preventing automatic conversions.

    The card states that coercion should be disabled "when you need to enforce strict data contracts" and the input data type must match the annotated type exactly. Option B is incorrect because coercion actually enables more flexible handling of diverse input formats by converting them to the target type, so disabling it would reduce flexibility.

    Read the full bite: Pydantic's Data Coercion: From Raw Data to Python Types

  30. Question 30 of 30

    For what primary purpose should model_config be used in Pydantic V2 models?

    Show the answer

    Answer: a · To apply model-wide settings like immutability or global string length constraints.

    model_config is designed for applying consistent, model-wide behaviors such as making a model immutable (frozen=True) or setting global string length limits. Option C describes the use case for Pydantic's Field function, not model_config.

    Read the full bite: Pydantic: Configuring Models with `model_config`

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