Python Middle cheat sheet: interview answers

Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.

  1. 1. What does yield turn a function into?

    Correct answer: A generator function that returns an iterator when called

    Calling it runs nothing yet. Each next() resumes the body until the next yield, so values are produced lazily.

  2. 2. What does this code print?

    gen = (x * 2 for x in range(3))
    print(list(gen))
    print(list(gen))

    Correct answer: [0, 2, 4], then []

    A generator can be consumed only once. After it's exhausted, iterating again yields nothing. Use a list if you need several passes.

  3. 3. Why is sum(x * x for x in range(10**7)) lighter on memory than sum([x * x for x in range(10**7)])?

    Correct answer: The generator produces values one at a time instead of building a list

    A list comprehension materializes ten million ints first. A generator expression keeps just one value in flight.

  4. 4. Which methods make an object an iterator?

    Correct answer: __iter__ and __next__, which raises StopIteration

    An iterable only needs __iter__ returning an iterator. An iterator also has __next__. for loops call both and stop on StopIteration.

  5. 5. What does yield from other_gen() do?

    Correct answer: Delegates to another generator and passes its values through

    It replaces for x in other: yield x and also forwards send(), throw() and the subgenerator's return value.

  6. 6. What is a decorator?

    Correct answer: A callable that takes a function and returns a replacement for it

    @deco above def f is shorthand for f = deco(f). Decorators usually wrap the original to add logging, caching or checks.

  7. 7. Why use functools.wraps inside a decorator?

    Correct answer: It copies the name and docstring to the wrapper

    Without it, the wrapped function reports the wrapper's __name__ and __doc__, which confuses logs, debuggers and docs tools.

  8. 8. How is a decorator with arguments, like @retry(times=3), built?

    Correct answer: A function that takes the arguments and returns the actual decorator

    retry(times=3) is called first, and its result is applied to the function. That's why there are three nested levels: factory, decorator, wrapper.

  9. 9. What does this code print?

    funcs = [lambda: i for i in range(3)]
    print([f() for f in funcs])

    Correct answer: [2, 2, 2]

    Closures capture the variable, not its value at creation time. When called, all lambdas see the final i. Bind it with lambda i=i: i.

  10. 10. What does @functools.lru_cache do?

    Correct answer: Remembers results for given arguments and returns them on repeat calls

    Arguments must be hashable. maxsize bounds the cache, and functools.cache is the unbounded version.

  11. 11. What does functools.partial(pow, exp=2) return?

    Correct answer: A new callable with exp=2 already filled in

    partial fixes some arguments and leaves the rest for later. square = partial(pow, exp=2) then square(5) returns 25.

  12. 12. Which methods does an object need to work with the with statement?

    Correct answer: __enter__ and __exit__

    __enter__ runs on entry and its result goes to as. __exit__ runs on exit and receives the exception details, if any.

  13. 13. What happens if __exit__ returns True?

    Correct answer: The exception raised in the block is suppressed

    A truthy return value tells Python the exception was handled. contextlib.suppress(FileNotFoundError) is built on this.

  14. 14. What does @contextlib.contextmanager let you write?

    Correct answer: A context manager as a generator with one yield

    Code before yield is the setup, after it the teardown. Wrap yield in try/finally so cleanup runs on errors too.

  15. 15. How do you give a dataclass field a fresh empty list for each instance?

    Correct answer: items: list[str] = field(default_factory=list)

    A mutable default like [] would be shared, so dataclass rejects it with a ValueError. default=list would store the list type itself. default_factory calls list() for every new object.

  16. 16. What does @dataclass(frozen=True) give you?

    Correct answer: Instances that can't be reassigned and are hashable

    Frozen dataclasses suit value objects and dict keys. dataclasses.replace(obj, x=1) makes a modified copy.

  17. 17. What does __slots__ do in a class?

    Correct answer: Fixes the attribute set and drops __dict__

    Without a __dict__, each instance takes less memory and attribute access is a bit faster. Assigning an unlisted attribute raises AttributeError.

  18. 18. What does @property let you do?

    Correct answer: Expose a method as an attribute, with optional setter logic

    You can start with a plain attribute and later add validation behind a property without changing callers' code.

  19. 19. What is the difference between @classmethod and @staticmethod?

    Correct answer: A classmethod gets the class as its first argument, a staticmethod gets nothing extra

    Classmethods are typical for alternative constructors like from_json, and they respect subclasses through cls.

  20. 20. What determines which parent method super() calls with multiple inheritance?

    Correct answer: The class's method resolution order (MRO)

    Python builds the MRO with C3 linearization. You can inspect it with Class.__mro__. super() calls the next class in that order.

  21. 21. What does inheriting from abc.ABC with an @abstractmethod achieve?

    Correct answer: The class can't be instantiated until a subclass implements that method

    Instantiation raises TypeError while any abstract method is unimplemented, so missing pieces fail early.

  22. 22. What is a typing.Protocol for?

    Correct answer: Describing an interface by methods, not inheritance

    Protocols are static duck typing: any class with matching methods satisfies the type checker.

  23. 23. What happens at runtime when you call def f(x: int) with f("hello")?

    Correct answer: It runs normally: annotations aren't enforced by Python

    Type hints are read by tools like mypy and IDEs. Libraries such as Pydantic can validate at runtime, but plain Python doesn't.

  24. 24. How do you annotate a value that may be a str or None in modern Python?

    Correct answer: str | None

    The | syntax works since 3.10. Optional[str] is the older equivalent.

  25. 25. When is typing.TypedDict a good fit?

    Correct answer: Describing dicts with known keys, like JSON payloads

    A TypedDict is still a plain dict at runtime. It just tells the type checker which keys exist and what types they hold.

  26. 26. If a class defines __eq__ but not __hash__, what happens?

    Correct answer: Its instances become unhashable

    Equal objects must have equal hashes, so Python sets __hash__ = None. Define __hash__ from the same fields if you need sets or dict keys.

  27. 27. What does collections.defaultdict(list) do on a missing key?

    Correct answer: Creates an empty list for the key and returns it

    It's convenient for grouping: groups[key].append(item) without checking first. Note that reading a key also inserts it.

  28. 28. What does Counter("banana").most_common(1) return?

    Correct answer: [('a', 3)]

    Counter counts hashable items. most_common(n) returns a list of (item, count) pairs, highest first.

  29. 29. Why use collections.deque for a queue instead of a list?

    Correct answer: Adding and removing at both ends is O(1)

    list.pop(0) shifts every item and is O(n). deque.popleft() is O(1), and maxlen makes a bounded buffer.

  30. 30. What does heapq provide?

    Correct answer: A min-heap on top of a plain list

    heappush and heappop are O(log n), and heap[0] is the smallest item. For a max-heap, push negated values. nlargest finds top-k.

  31. 31. Why must data be sorted before itertools.groupby?

    Correct answer: It groups only consecutive items with the same key

    Unlike SQL GROUP BY, groupby starts a new group every time the key changes. Sort by the same key first.

  32. 32. Python's sorted is stable. What does that mean?

    Correct answer: Items with equal keys keep their original relative order

    Stability enables multi-key sorts: sort by the secondary key first, then by the primary one.

  33. 33. What does the walrus operator := do?

    Correct answer: Assigns a value inside an expression and returns it

    Example: while (line := f.readline()):. It avoids calling the same thing twice, but overusing it hurts readability.

  34. 34. What does the * mean in def connect(host, *, timeout=10):?

    Correct answer: Arguments after it must be passed by keyword

    connect("db", 5) fails, connect("db", timeout=5) works. Keyword-only arguments keep call sites readable.

  35. 35. What does / mean in def f(a, b, /, c):?

    Correct answer: a and b can be passed only by position

    Positional-only parameters let a library rename them later without breaking callers. Many built-ins use this, like len(obj, /).

  36. 36. What does {**a, **b} produce for two dicts?

    Correct answer: A new dict where b's values win on shared keys

    Later unpacking overwrites earlier keys. Since 3.9, a | b does the same and a |= b updates in place.

  37. 37. What does the GIL in CPython prevent?

    Correct answer: Two threads running Python bytecode at the same time

    The GIL is released during blocking I/O, so threads still help for network calls. CPU-bound Python code doesn't speed up with threads on a standard build.

  38. 38. Which tool fits CPU-heavy pure Python work on a standard CPython build?

    Correct answer: multiprocessing or ProcessPoolExecutor

    Separate processes each have their own interpreter and GIL. The cost is data serialization between processes.

  39. 39. What does ThreadPoolExecutor.map suit best?

    Correct answer: Many I/O-bound calls, like HTTP requests

    Threads wait on I/O in parallel because the GIL is released while waiting. Results come back in input order.

  40. 40. What does await do inside an async def function?

    Correct answer: Pauses the coroutine and lets other tasks run

    asyncio is cooperative: control returns to the event loop at each await, and the loop runs other ready tasks.

  41. 41. What happens if you call time.sleep(5) inside a coroutine?

    Correct answer: The whole event loop freezes for five seconds

    Blocking calls stop the loop thread. Use await asyncio.sleep(5), async libraries, or asyncio.to_thread for blocking code.

  42. 42. What does asyncio.gather(a(), b(), c()) do?

    Correct answer: Runs the coroutines concurrently and returns their results in order

    Total time is about the slowest call, not the sum. With return_exceptions=True, errors come back as values instead of being raised.

  43. 43. What does calling a coroutine function without await do?

    Correct answer: Creates a coroutine object that never runs

    Python warns "coroutine was never awaited". To run it in the background, wrap it in asyncio.create_task and keep a reference.

  44. 44. What is asyncio.run(main()) for?

    Correct answer: Starting a loop, running main, closing the loop

    It's the usual entry point of an asyncio program. It can't be called from code that's already running inside a loop.

  45. 45. What is a pytest fixture?

    Correct answer: A function that prepares resources, injected by name

    A test that takes db as a parameter gets the result of the db fixture. Code after yield in a fixture runs as teardown.

  46. 46. What does scope="session" on a pytest fixture mean?

    Correct answer: It is created once for the whole test run and shared

    Wider scopes save time for expensive setup like a database container, but shared state can leak between tests.

  47. 47. What does @pytest.mark.parametrize do?

    Correct answer: Runs the same test with several sets of arguments

    Each argument set becomes a separate test with its own ID in the report, so one failing case doesn't hide others.

  48. 48. In app/service.py, from app.client import fetch is used. What should a test patch?

    Correct answer: app.service.fetch

    Patch the name where it's looked up. from ... import copies the reference into app.service, so patching app.client doesn't affect it.

  49. 49. What is pytest's monkeypatch fixture good for?

    Correct answer: Temporarily changing attributes or env vars in a test

    Changes made with monkeypatch.setattr or setenv are undone automatically after the test.

  50. 50. Why use logging instead of print in an application?

    Correct answer: Levels and outputs can be configured without code changes

    Handlers can send records to files or services, and levels like DEBUG can be turned off in production.

  51. 51. What is the recommended way to get a logger in a module?

    Correct answer: logger = logging.getLogger(__name__)

    Named loggers form a hierarchy by module path, so you can tune app.db separately. Libraries shouldn't configure handlers themselves.

  52. 52. Why write logger.info("user %s", user_id) instead of an f-string?

    Correct answer: Formatting is skipped when the level is disabled

    The message is built lazily. Log aggregators can also group records by the constant template.

  53. 53. What does raise NewError(...) from err do?

    Correct answer: Sets the original exception as the cause, shown in the traceback

    The traceback shows "The above exception was the direct cause...". from None hides the context when it adds nothing.

  54. 54. What should custom exceptions in an application usually inherit from?

    Correct answer: Exception, often via one base error class for the app

    A shared base like AppError lets callers catch all your errors at once. BaseException is for exits like KeyboardInterrupt.

  55. 55. What does this function return?

    def f():
        try:
            return 1
        finally:
            return 2

    Correct answer: 2

    finally runs after return 1 and its own return overrides it. It would also swallow an exception, which is why 3.14 warns about it.

  56. 56. What causes an ImportError with "partially initialized module"?

    Correct answer: A circular import between two modules

    Module A imports B while B imports a name from A that isn't defined yet. Fix it by moving shared code out, or importing inside a function.

  57. 57. What does __all__ in a module control?

    Correct answer: Which names from module import * exports

    It doesn't stop explicit imports of other names. It also documents the module's public API for tools and readers.

  58. 58. What is pyproject.toml for?

    Correct answer: Declaring a project's metadata, dependencies and build settings

    It replaced setup.py and setup.cfg as the standard. Tools like pytest, Ruff and mypy also read their config from it.

  59. 59. Why commit a lock file like uv.lock for an application?

    Correct answer: It pins exact versions, including transitive ones

    pyproject.toml usually holds ranges. The lock file makes every install reproducible, from a laptop to CI to production.

  60. 60. What does f"{total=}" print when total = 42?

    Correct answer: total=42

    The = specifier, added in 3.8, prints the expression and its value. It's handy for quick debugging.

  61. 61. Why is a is b unreliable for comparing integers?

    Correct answer: Only small ints are cached, so the result depends on the value

    CPython caches ints from -5 to 256. Two equal large ints may or may not be one object. Compare values with ==.

  62. 62. What does an Enum member compare equal to?

    Correct answer: Only itself, not its raw value

    Color.RED == 1 is False for a plain Enum. Use IntEnum or StrEnum if you need comparison with raw values.

  63. 63. What is the problem with datetime.now() without arguments in a backend?

    Correct answer: It returns a naive datetime with no timezone attached

    Naive and aware datetimes can't be compared, and the server's local zone is ambiguous. Use datetime.now(timezone.utc).

  64. 64. Why does json.dumps({"at": datetime.now()}) fail?

    Correct answer: json can't serialize datetime objects

    Convert it with .isoformat(), or pass default= to handle custom types. Pydantic and FastAPI do this for you.

  65. 65. What is the default timeout in requests.get(url)?

    Correct answer: None: it can wait forever

    Without timeout=, a stuck server can hang a worker indefinitely. Always pass a timeout in production code.

  66. 66. In FastAPI, what does declaring a parameter as a Pydantic model give you?

    Correct answer: The request body is parsed and validated, with a 422 error on bad input

    FastAPI uses type hints for parsing, validation and the OpenAPI schema. Invalid data never reaches your function.

  67. 67. What does Depends() do in FastAPI?

    Correct answer: Injects the result of a dependency function into the endpoint

    Dependencies handle shared logic like DB sessions or auth, and can be overridden in tests with app.dependency_overrides.

  68. 68. In FastAPI, a route uses a blocking DB driver. How should it be declared?

    Correct answer: As a plain def, so FastAPI runs it in a thread pool

    Blocking calls in an async def stall the event loop. Plain def routes run in a worker thread, keeping the loop free.

  69. 69. What causes the N+1 query problem in the Django ORM?

    Correct answer: Loading a related object for each row in a loop

    for b in Book.objects.all(): b.author.name runs one query per book. select_related("author") fetches them in one JOIN.

  70. 70. When should you use prefetch_related rather than select_related in Django?

    Correct answer: For many-to-many and reverse foreign key relations

    select_related does a SQL JOIN for single-valued relations. prefetch_related runs a second query and joins in Python.

  71. 71. When does a Django QuerySet actually hit the database?

    Correct answer: When it's evaluated, for example iterated or list()

    QuerySets are lazy, so chaining filters costs nothing. Evaluated results are cached on that QuerySet object.

  72. 72. What does copy.deepcopy do with an object that references itself?

    Correct answer: Copies it correctly, using a memo of copied objects

    deepcopy keeps a memo dict of copied objects. Classes can customize the behavior with __deepcopy__.

  73. 73. Why is "".join(parts) preferred over s += part in a long loop?

    Correct answer: Repeated += may copy the growing string each time

    Strings are immutable, so concatenation can be O(n^2) overall. Collect parts in a list and join once at the end.

  74. 74. What does @pytest.fixture(autouse=True) do?

    Correct answer: Applies the fixture to every test in its scope without asking for it

    It suits setup that every test needs, like resetting a cache. Use it sparingly: hidden fixtures make tests harder to read.

  75. 75. What should __eq__ return when it gets an object of an unsupported type?

    Correct answer: NotImplemented, so Python can try the other operand

    Python then tries the reflected method on the other object and falls back to identity for ==. Returning False blocks the other type from deciding.