Part 2 · Section 10

Context Managers

Almost every program acquires something it must later give back: an open file, a lock, a temporary setting, a redirected output stream, a timer that has to be stopped. Forgetting the “give back” half, or skipping it because an exception jumped past it, is one of the most common sources of subtle bugs. Python’s answer is the context manager and the with statement: you describe setup and teardown once, and the language guarantees the teardown runs no matter how the block ends.

In this section you’ll learn:

Lectures

  1. 01Context Managers in Python✓
  2. 02Caveat with Lazy Iterators✓
  3. 03Not Just a Context Manager✓
  4. 04Additional Uses✓
  5. 05Generators and Context Managers✓
  6. 06The contextmanager Decorator✓
  7. 07Nested Context Managers✓

Practice: quiz & exercises

12 quiz questions · 4 coding exercises

Go to practice →