[docs] `contextlib.contextmanager` should include example with exception-handling

Franklin? Lee leewangzhong+python at gmail.com
Fri Dec 11 15:27:19 EST 2015


(Link to docs: https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager)

I was surprised when I tried to use `contextmanager` with a block that
threw an exception. After flailing around a bit on the REPL, I read
the docs more carefully and saw that I had to wrap the `yield` with a
`try-finally` block.

I first learned about the `with` statement as a way to open files and
guarantee (to some extent) that they'll be closed even if something
went wrong. I associate `with` with C++'s RAII, where destructors are
used to guarantee things happening at the end of scope. With that
intuition, it was surprising to me that the default behavior did not
handle exceptions, er, for me.

I admit I could have been more careful, but maybe others have the same
intuition, and would benefit from try-finally standing out more (i.e.
an example) on that page.


More information about the docs mailing list