Hello friends, today I wanted to expand on context managers in the last of this two part series. If you missed the first part you can find it here
The code that I will be referencing can be found here.
In the first example you will see a context manager written in the form of a class. The two most import functions are the dunder enter and the dunder exit. You can think of the
__enter__ as being called when you start the context manager
with FileHandler('test.tx') as in_file: ...
and when your context manager has completed the
__exit__ function will be called. As you can see there isn't a whole lot of magic to using a class as a context manager.
Next you will see a function written as a context manager. Here you will need to use the
@contextmanager decorator from the contextlib package. This will allow your function to become a context manager. In This case you will notice that you have a try..except..else block for managing the connection. One thing to note is that the exception block is written so that it will catch all exceptions which is normally bad practice but in this case a normal pattern. The use of the else is so that we tell the story that we will need to close the file upon successful execution of the try block.
I know this was a short post but I wanted to quickly cover the code with a little more detail than what was provided by the repo.