February 2009
Intermediate to advanced
68 pages
1h 51m
English
Context managers allow us to simplify code by ensuring that certain operations are performed before and after a particular block of code is executed. The behavior is achieved because context managers define two special methods, __enter__() and __exit__(), that Python treats specially in the scope of a with statement. When a context manager is created in a with statement its __enter__() method is automatically called, and when the context manager goes out of scope after its with statement its __exit__() method is automatically called.
We can create our own custom context managers or use predefined ones—as we will see later in this subsection, the file objects returned by the built-in open() function are context ...
Read now
Unlock full access