Index Ai Academy
Glossary · Phase 7 · Software engineering

Context manager

Also written: context managers

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 a try/finally around every use to be sure the file gets closed. A context manager is any object that knows its own setup and cleanup. with calls 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.

Create a free account See what's in the lesson

Never trained an AI?

Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account.

Teach it to write