Context manager

An object used with the with statement that sets up and cleans up a resource automatically.

A context manager guarantees setup and cleanup around a block of code, using the with statement. The classic example is with open(...) as f: — the file is closed automatically when the block ends, even if an error is raised. You can write your own with contextlib.contextmanager or by defining __enter__ and __exit__.

Example
with open("notes.txt", "w") as f:   # opened here
    f.write("hello")
# file is closed automatically here, even on error
print("saved")
Output
saved

Where this shows up in real Python

You will use with for files, database connections, locks, and temporary changes that must be undone afterwards.

Context manager tools

  • with open(path) as f — auto-close a file
  • with a, b: — manage several resources at once
  • contextlib.contextmanager — write one from a generator
  • __enter__ / __exit__ — the methods that define one