What is a context manager: the with statement
Many operations have a beginning and an end that must be respected: opening and closing a file, locking and releasing a resource…
Learn to manage resources with the with statement. In this lesson you will see what a context manager is and how a resource is closed even when there are errors, create your own managers with classes (__enter__ and __exit__) and with the contextmanager decorator, use the contextlib utilities (suppress, redirect_stdout, ExitStack) and apply good practices in exercises such as transactions with rollback, temporary settings and logs that react to errors.
Many operations have a beginning and an end that must be respected: opening and closing a file, locking and releasing a resource…
For your own class to work with with you only need to define __enter__ and __exit__ . Let us see how they behave and what they…
Writing a class with two methods is a lot of code for something simple. The contextlib module offers the @contextmanager…
Besides @contextmanager , the contextlib module includes ready-made managers for very common situations. Knowing them avoids…
You already know how to create and use context managers. This last article gathers the habits that avoid mistakes and several…
Create a Python program with a class that is a context manager : an object that can be used with with thanks to the __enter__ and…
Create a Python program that nests several with blocks one inside another and shows each opening and closing with an indentation…
Create a Python program that captures what is printed with print inside a with block, using an io.StringIO object from the io…
Create a Python program with a context manager written as a generator function and the @contextmanager decorator from the…
Create a Python program that adds up numbers while ignoring texts that are not numbers, using suppress from the contextlib module…
Create a Python program that shows that a context manager is always closed , even when an error occurs inside the block, and that…
Create a Python program that simulates a bank transaction : if something goes wrong inside the block, the balance goes back to…
Create a Python program that changes a global setting only during a with block and restores it on exit, even if there is an error…
Create a Python program that opens a variable number of resources and closes them all at the end in reverse order. When you do…
Create a Python program with a context manager that decides according to the type of error : the parameters of __exit__ tell…