This answer key contains 4 multiple-choice, 4 fill-in-the-blank, and 4 output-prediction questions for Python Context Managers, with the exact answer and a short explanation for every question.
The answers are shown in full, so use this page after making an attempt. The practice page is the better first pass.
Which two methods make an object a context manager?
Answer: __enter__ and __exit__
Why: The with statement calls __enter__ before the body and __exit__ after it.
When is __exit__ called?
Answer: When the with block exits
Why: __exit__ runs whether the body succeeds or raises an exception.
What does the program output?
class C:
def __enter__(self):
return "ok"
def __exit__(self, *args):
pass
with C() as value:
print(value)Answer: ok
Why: The value returned by __enter__ is bound by the as clause.
What does contextlib.contextmanager require in the function?
Answer: One yield
Why: The code before yield is setup, and the code after yield is cleanup.
Complete the statement that opens a managed block.
____ open("note.txt", "w") as f:
f.write("hi")Answer: with
Why: with starts a managed block and guarantees cleanup.
Complete the setup method.
class C:
def ____(self):
return selfAnswer: __enter__
Why: __enter__ prepares the resource and returns the value bound by as.
Complete the cleanup method.
class C:
def ____(self, exc_type, exc, tb):
passAnswer: __exit__
Why: __exit__ runs when the with block ends.
Complete the keyword that separates setup from cleanup.
from contextlib import contextmanager
@contextmanager
def c():
____ 1Answer: yield
Why: contextmanager uses yield as the boundary between setup and cleanup.
What appears on the screen?
class C:
def __enter__(self):
return "ok"
def __exit__(self, *args):
return False
with C() as value:
print(value)Answer: ok
Why: The value from __enter__ is ok.
What is printed?
from contextlib import contextmanager
@contextmanager
def value():
yield 7
with value() as number:
print(number + 1)Answer: 8
Why: The manager yields seven, and seven plus one is eight.
What is the output?
class C:
def __enter__(self):
return 2
def __exit__(self, *args):
pass
with C() as n:
print(n * 3)Answer: 6
Why: The manager yields two, and two times three is six.
What does this code print?
from contextlib import contextmanager
@contextmanager
def label():
yield "x"
with label() as text:
print(text.upper())Answer: X
Why: The manager yields x, and upper makes it X.
Try the questions first
Open the practice page for Python Context Managers and answer the same 12 questions with instant feedback.