Skip to content
tezvyn:

Top 30 Python Interview Questions and Answers

30 multiple-choice questions on Python, drawn from 30 bites out of the 217 tagged Python on Tezvyn. 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.

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

    When you annotate a FastAPI route parameter with a Pydantic model, what does the framework do with that type hint?

    Show the answer

    Answer: a · It leverages the hint for automatic request validation and OpenAPI schema generation

    FastAPI reads type hints at startup to construct Pydantic models that validate incoming requests and generate OpenAPI schemas automatically. The distractor about runtime enforcement is wrong because Python itself ignores type hints during execution unless an external tool checks them.

    Read the full bite: Explain Python type hints and their importance in FastAPI

  3. Question 3 of 30

    When should you import an agent framework like CrewAI or LangGraph instead of building a plain Python workflow?

    Show the answer

    Answer: b · Only when the orchestration complexity genuinely demands dynamic planning beyond explicit control flow

    The card argues that agent frameworks should be an upgrade, not a starting point, and adopted only when orchestration complexity truly requires dynamic planning. Option C describes when to use plain Python, while D inverts the card's warning that letting the LLM own the execution graph inherits hallucinations rather than eliminating them.

    Read the full bite: Most LLM Apps Need Workflows Not Agent Frameworks

  4. Question 4 of 30

    You write an async def FastAPI endpoint that calls requests.get. What is the main risk?

    Show the answer

    Answer: c · The event loop is blocked, freezing concurrent request handling until the call finishes.

    The correct answer is C because calling a blocking library like requests inside async def stalls the event loop, stopping all other requests. The most tempting distractor is A because beginners often assume FastAPI magically threadpools any blocking code, but only def endpoints are run in a threadpool.

    Read the full bite: What is the difference between def and async def in Python and FastAPI?

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

  6. Question 6 of 30

    What mechanism triggers FastAPI to automatically validate and parse an incoming JSON request body against a schema?

    Show the answer

    Answer: b · Using a Pydantic model as the type hint for a route parameter

    FastAPI inspects function signature type hints at runtime, so using a Pydantic model as a parameter type hint automatically triggers request parsing and validation. Manually calling json.loads inside the route is a red flag that ignores this declarative mechanism, and response_model governs response serialization, not request validation.

    Read the full bite: How does FastAPI leverage Pydantic for request validation and serialization?

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

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

  9. Question 9 of 30

    When building an async execution-time decorator for FastAPI, why is omitting functools.wraps on the inner wrapper considered a red flag?

    Show the answer

    Answer: b · It strips the original function's metadata, which breaks FastAPI's OpenAPI schema generation and dependency injection.

    functools.wraps preserves the original function's name, signature, and metadata, which FastAPI relies on to generate OpenAPI docs and resolve dependencies; omitting it exposes the wrapper's metadata instead. Distractor A is wrong because wraps has no effect on whether code runs synchronously or blocks the event loop.

    Read the full bite: Write an async decorator that logs execution time for FastAPI

  10. Question 10 of 30

    Which implementation correctly minimizes total latency when a FastAPI endpoint must fetch data from two independent external APIs?

    Show the answer

    Answer: a · Inside an async def endpoint, pass two httpx.AsyncClient coroutines to asyncio.gather and await the result.

    asyncio.gather with an async HTTP client schedules both I/O-bound coroutines concurrently on the event loop, reducing total latency to roughly the slower call. Option C is tempting because it uses async/await correctly, but sequential awaiting means the second request cannot start until the first finishes, so latencies add up.

    Read the full bite: How do you structure concurrent API calls with asyncio.gather in FastAPI?

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

  12. Question 12 of 30

    When a FastAPI endpoint awaiting asyncpg is suspended during a database query, how can Uvicorn process another incoming connection in the same worker process?

    Show the answer

    Answer: d · The event loop yields the coroutine at the await, registers the socket with epoll or kqueue, and schedules the new connection's coroutine on the same thread.

    The correct answer describes cooperative multitasking: the event loop suspends the coroutine at await and interleaves I/O-bound tasks on a single thread. Distractor A is wrong because Uvicorn does not use multiple Python threads to handle requests; concurrency comes from the loop scheduling coroutines, not from threading or GIL behavior.

    Read the full bite: How does Uvicorn use asyncio to handle thousands of concurrent connections?

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

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

  15. Question 15 of 30

    In FastAPI, why should an async database session dependency wrap yield in try and place await session.close() in finally?

    Show the answer

    Answer: a · It guarantees cleanup runs even if the path operation raises an exception.

    A try/finally block guarantees that await session.close() runs even when the path operation raises an exception, preventing database connection leaks. The thread pool issue in distractor C is caused by using def instead of async def, not by omitting exception handling.

    Read the full bite: Implement an async database session dependency using yield for setup and teardown

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

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

  18. Question 18 of 30

    When an incoming GET request reaches a FastAPI app, how does @app.get("/") enable the correct function to run?

    Show the answer

    Answer: d · It registers the function in the app's route table at import time and generates OpenAPI metadata.

    The decorator actively registers the function for GET / in the app's internal route table when the module is imported and simultaneously populates the OpenAPI schema, enabling the ASGI layer to dispatch matching requests. Calling it pure syntax sugar is a common misconception because it fundamentally alters the application's routing registry and automatic documentation rather than leaving framework behavior unchanged.

    Read the full bite: What is the purpose of @app.get("/") in FastAPI?

  19. Question 19 of 30

    Which approach correctly defines a FastAPI endpoint that captures an integer item_id from a URL like /items/42?

    Show the answer

    Answer: a · Use app.get("/items/{item_id}") and define async def read_item(item_id: int): then use item_id directly inside the function

    FastAPI binds curly-braced path segments to function arguments with matching names and type hints, automatically converting and injecting the value. Option B is tempting because the route syntax is correct, but the mismatched argument name breaks the default binding unless you use a Path alias.

    Read the full bite: How do you define and access a FastAPI path parameter?

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

  21. Question 21 of 30

    Which FastAPI endpoint declaration identifies a user in the URL path and accepts an optional search term after the question mark?

    Show the answer

    Answer: a · Route /users/{user_id}/items with user_id in path and q optional

    Option A correctly places the user identifier in the path template and gives q a default of None so it becomes an optional query parameter. Option B is tempting because it also makes q optional, but it omits user_id from the path so FastAPI treats it as a query parameter, violating RESTful hierarchy.

    Read the full bite: What is the difference between a path parameter and a query parameter?

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

  23. Question 23 of 30

    An endpoint declares a query parameter as q: Optional[str] with no default value. What happens when a client omits it?

    Show the answer

    Answer: c · FastAPI returns a 422 Unprocessable Entity error

    FastAPI derives requirement from the presence or absence of a Python signature default, not from type hints, so Optional[str] without = None is still required and omitting it triggers a 422 error. Option D is a common misconception because Optional alone does not make a parameter optional in FastAPI.

    Read the full bite: How does FastAPI distinguish required optional and default query parameters

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

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

  26. Question 26 of 30

    What combination of standard and code sources enables FastAPI's automatic interactive documentation?

    Show the answer

    Answer: d · It dynamically builds an OpenAPI schema from type hints, Pydantic models, decorators, and docstrings

    FastAPI dynamically generates an OpenAPI schema by extracting metadata from type hints, Pydantic models, decorators, and docstrings, so no manual schema file is required. Option B is wrong because maintaining a separate openapi.yaml by hand is unnecessary and contradicts FastAPI's design.

    Read the full bite: What standard and code elements power FastAPI's auto-generated API docs?

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

  28. Question 28 of 30

    A client sends GET /items?limit=foo to an endpoint with parameter limit: int. What is FastAPI's default response?

    Show the answer

    Answer: a · HTTP 422 Unprocessable Entity with a JSON body whose detail array contains objects with loc, msg, and type fields

    FastAPI relies on Pydantic to automatically validate query parameters and returns a 422 Unprocessable Entity with a JSON detail array of objects containing loc, msg, and type fields. Option B is tempting because the status code is correct, but the body structure is actually a detailed array rather than a single string.

    Read the full bite: FastAPI non-integer query param default behavior

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

  30. Question 30 of 30

    To accept multiple values for a single query key and allow per-item length constraints in current FastAPI, which parameter declaration should you use?

    Show the answer

    Answer: c · tag: Annotated[list[str], Query()] = []

    Annotated[list[str], Query()] = [] is the modern pattern that separates validation metadata from the default value, enabling per-item constraints. tag: list[str] = Query(default=[]) is the outdated alternative that mixes the default with validation metadata.

    Read the full bite: How do you type-hint repeated query params in FastAPI?

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