Context manager (with)

Applies to: python

A context manager (used via with) guarantees setup and cleanup around a block, even if an error occurs, the Python analog of C++ RAII. The classic use is files, which are closed automatically on exit.

with open("data.csv") as f:   # opened
    text = f.read()
# f is closed here, automatically, even on error

See also: exception