The Python "with" Statement by Example
Python’s with statement was first introduced five years ago, in Python 2.5. It’s handy when you have two related operations which you’d like to execute as a pair, with a block of code in between. The classic example is opening a file, manipulating the file, then closing it: with open('output.txt', 'w') as f: f.write('Hi there!') The above with statement will automatically close the file after the nested block of code. (Continue reading to see exactly how the close occurs.) Here’s another example. This code sample uses a Context object (“cairo context”) to draw six rectangles, each with a different rotation. cr.translate(68, 68) for i in xrange(6): cr.save() cr.rotate(2 * math.pi * i / 6) cr.rectangle(-25, -60, 50, 40) cr.stroke() cr.restore() That’s a fairly simple example, but for larger scripts, it can become cumbersome to keep track of which save goes with which restore, and to keep them correctly matched. Implementing the Context Manager as a Class Here’s the first approach. Uh oh!
Related: Advanced Topics
• Machine learning en python