Congratulations! We have reached the end of the context managers lesson. Making it this far means that we have explored many of the core concepts behind context managers. Let’s recap:
- Context managers are a form of resource management in python invoked by the
- They ensure that resources are closed/released after usage regardless of whether or not an error occurs.
- They can be created from scratch using either the class-based method or the
- Behind every context manager, there’s an
__exit__method taking place.
- Context managers can be nested together to work with resources simultaneously.
Class-Based Context Managers
- They can be created from scratch with the manual implementation of the
__exit__method takes three arguments: An exception type, exception value, and a traceback. The method can then handle exceptions.
Decorator Based Context Managers
- They can be created from scratch using the
contextlibcontextmanager decorator on a generator function
- In the
exceptblock handles exception’s code block