Answer key · 12 questions

Python Context Managers Exercises With Answers

All 12 questions for Python Context Managers in one place. Try the practice page first, then use this page to check the exact answer and the reason.

Quick answer

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.

01 · Multiple choice

Which two methods make an object a context manager?

  1. __init__ and __repr__
  2. __enter__ and __exit__correct
  3. __iter__ and __next__
  4. __get__ and __set__

Answer: __enter__ and __exit__

Why: The with statement calls __enter__ before the body and __exit__ after it.

02 · Multiple choice

When is __exit__ called?

  1. When the with block exitscorrect
  2. Only when the file is empty
  3. Only when __enter__ fails
  4. Before __enter__

Answer: When the with block exits

Why: __exit__ runs whether the body succeeds or raises an exception.

03 · Multiple choice

What does the program output?

class C:
    def __enter__(self):
        return "ok"
    def __exit__(self, *args):
        pass
with C() as value:
    print(value)
  1. C
  2. okcorrect
  3. None
  4. True

Answer: ok

Why: The value returned by __enter__ is bound by the as clause.

04 · Multiple choice

What does contextlib.contextmanager require in the function?

  1. One return
  2. One yieldcorrect
  3. One class
  4. One print

Answer: One yield

Why: The code before yield is setup, and the code after yield is cleanup.

05 · Fill in the blank

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.

06 · Fill in the blank

Complete the setup method.

class C:
    def ____(self):
        return self

Answer: __enter__

Why: __enter__ prepares the resource and returns the value bound by as.

07 · Fill in the blank

Complete the cleanup method.

class C:
    def ____(self, exc_type, exc, tb):
        pass

Answer: __exit__

Why: __exit__ runs when the with block ends.

08 · Fill in the blank

Complete the keyword that separates setup from cleanup.

from contextlib import contextmanager
@contextmanager
def c():
    ____ 1

Answer: yield

Why: contextmanager uses yield as the boundary between setup and cleanup.

09 · Predict output

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.

10 · Predict output

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.

11 · Predict output

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.

12 · Predict output

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.

Practice this lesson