Context Managers 'with'
In other programming languages we use the try/expect/finally
block to handle resource or to manage those resources, in python we can use the with
statement and context managers to simplify that operation
Here and example in of how try
statement is use to handle open and close a file
Now the same operation but using the with
statement
the context manager will take care of opening the file and later close it when we are done.
Usages of with
statement¶
Database¶
Locks¶
TensorFlow¶
Context Manager¶
Although the definition of context manager was a bit confusing for me the first time i read it, it make sense with the time. A context Manager is an object that defines the runtime context to be establish when executing a with
statement.
The context manager will handle the enter into, and exit from a desired runtime.
The Syntax¶
with
andas
are keywordsVAR
is just a variable it can be use to call the result of the expressionBlock
just the block of code.
Implementing a Context manager¶
Like in everything we can create our own implementation of a context manager. There are two ways to do it:
- User-defined classes.
- Generators.
User-defined Classes¶
to implement a context manager we will need to create a class that contain two methods __enter__()
and __exit__()
.
Few things to remark in the example:
- We have two variables
file_name
andmode
.mode
is how we wnat to open the file, write mode or read mode. - In the method
__enter__()
we open the file. - In the method
__exit__()
whe make sure to close the file.
In some cases we can use this implementation to handle exceptions.
Implementing the context manager with generator¶
To implemented in this way we will need the library contextlib.contextmanager
this library will provide a decorator @contextmanager
If a generator function is decorated with the contextlib.contextmanager
decorator, it will return a context manager implementing the necessary__enter__()
and __exit__()
methods.
__enter__()
method. and the code after the yield statement is equivalent to__exit__()
method.