Gregory Szorc <gregory.szorc@gmail.com> [Sat, 02 Jan 2016 16:41:57 -0800] rev 27704
osutil: implement __enter__ and __exit__ on posixfile
So they can be used as context managers.
Bryan O'Sullivan <bos@serpentine.com> [Mon, 11 Jan 2016 15:25:43 -0800] rev 27703
util: introduce ctxmanager, to avoid nested try/finally blocks
This is similar in spirit to contextlib.nested in Python <= 2.6,
but uses an extra level of indirection to avoid its inability to
clean up if an __enter__ method raises an exception.
Why add this mechanism? It greatly simplifies scoped resource
management, and lets us eliminate several hundred lines of try/finally
blocks. In many of these cases the "finally" is separated from the
"try" by hundreds of lines of code, which makes the connection
between resource acquisition and disposal difficult to follow.
(The preferred mechanism would be the "multi-with" syntax of 2.7+,
but Mercurial can't move to 2.7 for a while.)
Intended use:
>>> with ctxmanager(lambda: file('foo'), lambda: file('bar')) as c:
>>> f1, f2 = c()
This will open both foo and bar when c() is invoked, and will close
both upon exit from the block. If the attempt to open bar raises
an exception, the block will not be entered - but foo will still
be closed.