Context Managers

with, __enter__ / __exit__, and @contextmanager

30 min · interactive lesson with runnable code and 5 graded exercises.

What you'll be able to do

  • Explain what with does step by step
  • Write a class with __enter__ and __exit__
  • Know what __exit__'s arguments and return value mean
  • Write a context manager with @contextmanager — cleanup in finally

The full lesson is free with an account.

The with statement

__enter__ and __exit__

Writing your own

@contextmanager

In ML code

Common pitfalls