Python Tutorial #15: Context Managers — with Statement and Resource Management
In the previous tutorial, we learned about decorators. Now let’s learn about context managers — the mechanism behind the with statement. You have been using with since the file I/O tutorial: with open("file.txt") as f: content = f.read() # File is automatically closed here But what actually happens behind the scenes? And how do you create your own with-compatible objects? By the end of this tutorial, you will understand the protocol behind context managers and know how to build your own for resource management, timing, transactions, and more. ...