[Python-ideas] PEP 380 close and contextmanagers?

Nick Coghlan ncoghlan at gmail.com
Thu Oct 28 00:00:36 CEST 2010

On Thu, Oct 28, 2010 at 2:18 AM, Ron Adam <rrr at ronadam.com> wrote:
> It looks like No context managers return values in the finally or __exit__
> part of a context manager.  Is there way to do that?

The return value from __exit__ is used to decide whether or not to
suppress the exception (i.e. bool(__exit__()) == True will suppress
the exception that was passed in).

There are a few CMs in the test suite (test.support) that provide info
about things that happened during their with statement - they all use
the trick of returning a stateful object from __enter__, then
modifying the attributes of that object in __exit__. I seem to recall
the CM variants of unittest.TestCase.assertRaises* doing the same
thing (so you can poke and prod at the raised exception yourself).
warnings.catch_warnings also appends encountered warnings to a list
returned by __enter__ when record=True.


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list