Salai Vedha Viradhan writes:
If you have ever used Python, you would have definitely come across the 'with' statement. It’s widely used when reading from or writing to files on the disk. But, ever wondered what are we getting out of using the 'with' statement exactly?
The 'with' statement allows us to create a context manager (not related to bpy.context in Blender) in Python. Context managers solve the problem of ‘setup’ and ‘teardown’. The ‘setup’ is done when you enter into a with block and the ‘teardown’ is done when you leave its scope.
Context managers can help us greatly eliminate repetitive boilerplate from our code by taking care of ‘setup’ and ‘teardown’.
Here’s how you can implement your own: