Context Manager
noun
say it: “KON-tekst MAN-ih-jer” /ˈkɑntɛkst ˈmænɪdʒər/
In Python, an object used with a with block that sets something up at the start and cleans it up at the end, even if an error happens.
What is a context manager?
A context manager sets something up when a with block starts and cleans it up when the block ends, even if an error happens. Files are the everyday example.
with open("report.txt", "w") as file: # set up: open the file
file.write("Sales are up")
# clean up: the file is closed here, even after an error
In a sentence
- “open() is a context manager, so the file closes when the with block ends.”
- “FastAPI's lifespan function is written as a context manager.”
Level: Freelancer · More Python terms at this level
Updated