Glossary · Phase 7 · Software engineering
Context manager
An object used with a with statement that sets something up at the start and always cleans up at the end.
Without
with, you'd need atry/finallyaround every use to be sure the file gets closed. A context manager is any object that knows its own setup and cleanup.withcalls them at the right moments.
Try it now
Step through to see the order: __enter__ runs first and its return value becomes status, the block runs, then __exit__ runs with None for the error.
Learn it properly
Context managers · Setup and cleanup that always run: with, contextlib, transactions and atomic writes. About 35 minutes.
Never trained an AI?
Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account.