Caffeinated Coder
Book an appointment
Lesson 23 · Idiomatic Python

Context managers

A context manager is an object that sets something up and is guaranteed to clean it up again: close the file, release the lock, turn the lights off. Step through the with statement as Python runs it: it makes the manager, calls __enter__, binds its return value with as, runs the block, and calls __exit__ even when the block fails. Then see how __exit__'s return value decides whether an error is swallowed, and write the same manager in five lines with @contextmanager.

14 min11 steps5 questionsAdvanced
Fig 23 · Interactive
Loading figure…
or ← →

Quiz Unlocks after the last step.