Quiz · Hard
Late-binding closures, shared defaults, try/finally, class attributes, decorators and wraps, generators, MRO, properties, context managers and lru_cache.
What does this code print?
fs = [lambda: i for i in range(3)]
print([f() for f in fs])[0, 1, 2]
[2, 2, 2]
[3, 3, 3]
[1, 2, 3]
The lambdas capture the variable i, not its value at creation time. When called after the loop, i is 2 for all of them. lambda i=i: i would bind the current value.
What does this code print?
def f(x, acc=[]):
acc.append(x)
return acc
print(f(1), f(2))[1, 2] [1, 2]
[1] [2]
[1] [1, 2]
[2] [1, 2]
The default list is created once and shared by every call. The first call returns that same list object, which has grown to [1, 2] by the time print shows it, so both outputs are [1, 2].
What does this code print?
def f():
try:
return "try"
finally:
print("cleanup")
print(f())try, then cleanup
try (cleanup never runs after return)
cleanup is skipped because of the return
cleanup, then try
finally runs before the function actually returns, so cleanup is printed first, then print shows the returned value try.
What does this code print?
class A:
x = 1
a = A()
b = A()
A.x = 2
a.x = 5
print(a.x, b.x, A.x)5 5 2
2 2 2
5 2 2
5 1 2
a.x = 5 creates an instance attribute shadowing the class attribute for a only. b and the class still see 2.
What does this code print?
import functools
def deco(f):
@functools.wraps(f)
def wrapper(*a, **k):
return f(*a, **k)
return wrapper
@deco
def add(x, y):
"Add two numbers."
return x + y
print(add.__name__, add.__doc__)wrapper None
add Add two numbers.
add None
wrapper Add two numbers.
functools.wraps copies the wrapped function's name and docstring onto the wrapper. Without it you would see wrapper and None.
What does this code print?
def count():
yield 1
yield 2
g = count()
print(next(g), next(g), next(g, "done"))1 2 3
1 2 StopIteration
1 2 done
1 2 None
The third next() would raise StopIteration, but passing a default value makes next() return that default instead.
What does this code print?
class A:
def hi(self):
return "A"
class B(A):
def hi(self):
return "B>" + super().hi()
class C(A):
def hi(self):
return "C>" + super().hi()
class D(B, C):
pass
print(D().hi())B>C>A
B>A
C>B>A
D>B>C>A
The MRO of D is D, B, C, A, object. B.hi calls super().hi(), which resolves to C.hi (the next class in the MRO), and C.hi calls A.hi. Result: B>C>A.
What does this code print?
class T:
def __init__(self):
self._v = 3
@property
def v(self):
return self._v * 2
t = T()
print(t.v)
t.v = 106, then 10 is assigned silently
3, then an AttributeError
6, then the program ends normally with t.v unchanged
6, then an AttributeError (property has no setter)
t.v calls the getter and gives 6. Assigning to a property without a setter raises AttributeError ("property 'v' of 'T' object has no setter").
What does this code print?
def outer():
n = 0
def inc():
nonlocal n
n += 1
return n
return inc
i = outer()
j = outer()
print(i(), i(), j())1 2 3
1 2 1
1 1 1
2 3 1
Each call to outer creates its own variable n. i's closure counts 1, 2; j has a separate n starting again at 1.
What does this code print?
class R:
def __enter__(self):
print("open")
return self
def __exit__(self, *args):
print("close")
return False
try:
with R():
print("body")
raise ValueError("x")
except ValueError:
print("caught")open, body, close, caught
open, body, caught (close is skipped)
open, close, body, caught
open, body, caught, close
__exit__ always runs when the with block ends, even on an exception. Returning False lets the exception propagate, so caught is printed afterwards.
What does this code print?
def f(a, /, b, *, c):
return (a, b, c)
print(f(1, b=2, c=3))TypeError because a was given by position
TypeError because b must be positional
(1, 3, 2)
(1, 2, 3)
a is positional-only, b may be either, and c is keyword-only. The call matches: 1 positionally, b and c by keyword.
What does this code print?
import functools
@functools.lru_cache(maxsize=None)
def sq(n):
print("computing", n)
return n * n
print(sq(3), sq(3))computing 3 twice, then 9 9
9 9, then computing 3
computing 3 once, then 9 9
9 9 only, because nothing is computed
The first call computes and prints; the second is served from the cache without running the body. The line computing 3 appears once, before the final 9 9.
Which statement about type hints is true?
Passing a str to an int-annotated parameter raises TypeError
They are not enforced at runtime by Python itself; tools like mypy check them
They make code run faster
They are required for dataclasses to work
Annotations are metadata. Python ignores them when running your code, but static checkers, editors and libraries (dataclasses, pydantic) use them. Dataclasses need annotations for fields, but the types themselves are not checked.