Skills101
← All practice quizzes

Quiz: Context Managers

5 questions · new set on every retakeNo time limitPass: 60%+10 XP on first pass

The with statement guarantees clean-up, even when an error happens. See how it works with files, write your own context manager as a class or with contextlib, and use the handy built-in ones.

Log in to take the quiz

Free account · see your score, answers and explanations, earn XP

  1. Question 1

    What is the main benefit of with open(...) as f:?

  2. Question 2

    Which two methods make an object a context manager?

  3. Question 3

    In with Thing() as t:, what is stored in t?

  4. Question 4

    What does this print?

    class C:
        def __enter__(self):
            print("in")
            return self
        def __exit__(self, *a):
            print("out")
    with C():
        print("body")
    
  5. Question 5

    What happens if __exit__ returns True after an exception in the block?

🎯 Today’s placement challenge — 10 questions, no login. Can you score 10/10?Take today’s challenge →