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. What does
yieldturn 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 nextyield, so values are produced lazily.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. Why is
sum(x * x for x in range(10**7))lighter on memory thansum([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. Which methods make an object an iterator?
Correct answer:
__iter__and__next__, which raisesStopIterationAn iterable only needs
__iter__returning an iterator. An iterator also has__next__.forloops call both and stop onStopIteration.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 xand also forwardssend(),throw()and the subgenerator's return value.6. What is a decorator?
Correct answer: A callable that takes a function and returns a replacement for it
@decoabovedef fis shorthand forf = deco(f). Decorators usually wrap the original to add logging, caching or checks.7. Why use
functools.wrapsinside 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. 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. 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 withlambda i=i: i.10. What does
@functools.lru_cachedo?Correct answer: Remembers results for given arguments and returns them on repeat calls
Arguments must be hashable.
maxsizebounds the cache, andfunctools.cacheis the unbounded version.11. What does
functools.partial(pow, exp=2)return?Correct answer: A new callable with
exp=2already filled inpartialfixes some arguments and leaves the rest for later.square = partial(pow, exp=2)thensquare(5)returns 25.12. Which methods does an object need to work with the
withstatement?Correct answer:
__enter__and__exit____enter__runs on entry and its result goes toas.__exit__runs on exit and receives the exception details, if any.13. What happens if
__exit__returnsTrue?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. What does
@contextlib.contextmanagerlet you write?Correct answer: A context manager as a generator with one
yieldCode before
yieldis the setup, after it the teardown. Wrapyieldintry/finallyso cleanup runs on errors too.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, sodataclassrejects it with aValueError.default=listwould store thelisttype itself.default_factorycallslist()for every new object.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. 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 raisesAttributeError.18. What does
@propertylet 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. What is the difference between
@classmethodand@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 throughcls.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. What does inheriting from
abc.ABCwith an@abstractmethodachieve?Correct answer: The class can't be instantiated until a subclass implements that method
Instantiation raises
TypeErrorwhile any abstract method is unimplemented, so missing pieces fail early.22. What is a
typing.Protocolfor?Correct answer: Describing an interface by methods, not inheritance
Protocols are static duck typing: any class with matching methods satisfies the type checker.
23. What happens at runtime when you call
def f(x: int)withf("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. How do you annotate a value that may be a
strorNonein modern Python?Correct answer:
str | NoneThe
|syntax works since 3.10.Optional[str]is the older equivalent.25. When is
typing.TypedDicta 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. 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. 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. What does
Counter("banana").most_common(1)return?Correct answer: [('a', 3)]
Countercounts hashable items.most_common(n)returns a list of(item, count)pairs, highest first.29. Why use
collections.dequefor 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), andmaxlenmakes a bounded buffer.30. What does
heapqprovide?Correct answer: A min-heap on top of a plain list
heappushandheappopare O(log n), andheap[0]is the smallest item. For a max-heap, push negated values.nlargestfinds top-k.31. Why must data be sorted before
itertools.groupby?Correct answer: It groups only consecutive items with the same key
Unlike SQL
GROUP BY,groupbystarts a new group every time the key changes. Sort by the same key first.32. Python's
sortedis 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. 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. What does the
*mean indef 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. What does
/mean indef f(a, b, /, c):?Correct answer:
aandbcan be passed only by positionPositional-only parameters let a library rename them later without breaking callers. Many built-ins use this, like
len(obj, /).36. What does
{**a, **b}produce for two dicts?Correct answer: A new dict where
b's values win on shared keysLater unpacking overwrites earlier keys. Since 3.9,
a | bdoes the same anda |= bupdates in place.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. Which tool fits CPU-heavy pure Python work on a standard CPython build?
Correct answer:
multiprocessingorProcessPoolExecutorSeparate processes each have their own interpreter and GIL. The cost is data serialization between processes.
39. What does
ThreadPoolExecutor.mapsuit 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. What does
awaitdo inside anasync deffunction?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. 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, orasyncio.to_threadfor blocking code.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. What does calling a coroutine function without
awaitdo?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_taskand keep a reference.44. What is
asyncio.run(main())for?Correct answer: Starting a loop, running
main, closing the loopIt's the usual entry point of an asyncio program. It can't be called from code that's already running inside a loop.
45. What is a pytest fixture?
Correct answer: A function that prepares resources, injected by name
A test that takes
dbas a parameter gets the result of thedbfixture. Code afteryieldin a fixture runs as teardown.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. What does
@pytest.mark.parametrizedo?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. In
app/service.py,from app.client import fetchis used. What should a test patch?Correct answer:
app.service.fetchPatch the name where it's looked up.
from ... importcopies the reference intoapp.service, so patchingapp.clientdoesn't affect it.49. What is pytest's
monkeypatchfixture good for?Correct answer: Temporarily changing attributes or env vars in a test
Changes made with
monkeypatch.setattrorsetenvare undone automatically after the test.50. Why use
logginginstead ofprintin 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. 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.dbseparately. Libraries shouldn't configure handlers themselves.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. What does
raise NewError(...) from errdo?Correct answer: Sets the original exception as the cause, shown in the traceback
The traceback shows "The above exception was the direct cause...".
from Nonehides the context when it adds nothing.54. What should custom exceptions in an application usually inherit from?
Correct answer:
Exception, often via one base error class for the appA shared base like
AppErrorlets callers catch all your errors at once.BaseExceptionis for exits likeKeyboardInterrupt.55. What does this function return?
def f(): try: return 1 finally: return 2Correct answer: 2
finallyruns afterreturn 1and its ownreturnoverrides it. It would also swallow an exception, which is why 3.14 warns about it.56. What causes an
ImportErrorwith "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. What does
__all__in a module control?Correct answer: Which names
from module import *exportsIt doesn't stop explicit imports of other names. It also documents the module's public API for tools and readers.
58. What is
pyproject.tomlfor?Correct answer: Declaring a project's metadata, dependencies and build settings
It replaced
setup.pyandsetup.cfgas the standard. Tools like pytest, Ruff and mypy also read their config from it.59. Why commit a lock file like
uv.lockfor an application?Correct answer: It pins exact versions, including transitive ones
pyproject.tomlusually holds ranges. The lock file makes every install reproducible, from a laptop to CI to production.60. What does
f"{total=}"print whentotal = 42?Correct answer: total=42
The
=specifier, added in 3.8, prints the expression and its value. It's handy for quick debugging.61. Why is
a is bunreliable 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. What does an
Enummember compare equal to?Correct answer: Only itself, not its raw value
Color.RED == 1is False for a plainEnum. UseIntEnumorStrEnumif you need comparison with raw values.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. Why does
json.dumps({"at": datetime.now()})fail?Correct answer:
jsoncan't serializedatetimeobjectsConvert it with
.isoformat(), or passdefault=to handle custom types. Pydantic and FastAPI do this for you.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. 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. 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. 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 poolBlocking calls in an
async defstall the event loop. Plaindefroutes run in a worker thread, keeping the loop free.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.nameruns one query per book.select_related("author")fetches them in one JOIN.70. When should you use
prefetch_relatedrather thanselect_relatedin Django?Correct answer: For many-to-many and reverse foreign key relations
select_relateddoes a SQL JOIN for single-valued relations.prefetch_relatedruns a second query and joins in Python.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. What does
copy.deepcopydo with an object that references itself?Correct answer: Copies it correctly, using a memo of copied objects
deepcopykeeps a memo dict of copied objects. Classes can customize the behavior with__deepcopy__.73. Why is
"".join(parts)preferred overs += partin a long loop?Correct answer: Repeated
+=may copy the growing string each timeStrings are immutable, so concatenation can be O(n^2) overall. Collect parts in a list and join once at the end.
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. What should
__eq__return when it gets an object of an unsupported type?Correct answer:
NotImplemented, so Python can try the other operandPython then tries the reflected method on the other object and falls back to identity for
==. ReturningFalseblocks the other type from deciding.