Context managers
In this section, we'll look at what is maybe Python's most-used programmable semantic elementâcontext managers.
Context managers are pieces of code that plug into Python's with
statement. A with
statement contains a block of code, and the context manager is able to run its own code, both before and after that block is executed, along with the after code guaranteed to run no matter what happens in the block.
The Python standard library makes quite a lot of use of context managers:
open
files can be used as context managers, which guarantees that the file will be closed at the end of the block:

lock
objects could be used as context managers, in which case they acquire the lock before the block and release it when the block is finished executing:

- SQLite database connections can be used as context managers, allowing them to automatically commit or roll back the transaction when the block finishes:

There are other examples. We can already see in the preceding examples how useful...