Context managers
When working with external resources, we usually need to perform some cleanup steps, when we are done. For example, after writing data to a file, we then need to close the file. Failing to clean up properly could result in all manner of bugs. Therefore, we must ensure that our cleanup code will be executed even if an exception happens. We could use try
/finally
statements, but this is not always convenient and could result in a lot of repetition, as we often have to perform similar cleanup steps whenever we work with a particular type of resource. Context managers solve this problem by creating an execution context in which we can work with a resource and automatically perform any necessary cleanup when we leave that context, even if an exception was raised.
Another use case of context managers is to make temporary changes to the global state of our program. One example of global state that we may want to modify temporarily is the precision for decimal computations. For...