[New-bugs-announce] [issue4589] 'with' loses ->bool exceptions

Jeffrey Yasskin report at bugs.python.org
Mon Dec 8 07:21:10 CET 2008

New submission from Jeffrey Yasskin <jyasskin at gmail.com>:

When a context manager's __exit__() method returns an object whose
conversion to bool raises an exception, 'with' loses that exception. For

>>> class CM(object):
...   def __init__(self, exit_result):
...     self.exit_result = exit_result
...   def __enter__(self):
...     return 3
...   def __exit__(self, a, b, c):
...     return self.exit_result()
>>> class TrueAsBool(object):
...   def __nonzero__(self): return True
>>> class FalseAsBool(object):
...   def __nonzero__(self): return False
>>> class FailAsBool(object):
...   def __nonzero__(self):
...     raise RuntimeError("Should see this but won't")
>>> with CM(TrueAsBool):
...   raise AssertionError("Should NOT see this")
>>> with CM(FalseAsBool):
...   raise AssertionError("Should see this")
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
AssertionError: Should see this
>>> with CM(FailAsBool):
...   raise AssertionError("Should see RuntimeException (oops)")

The problem is that WITH_CLEANUP only checks if PyObject_IsTrue(x)
returns non-zero, but that function returns <0 when the bool conversion
raises an exception.

assignee: jyasskin
components: Interpreter Core
messages: 77290
nosy: jyasskin
severity: normal
stage: needs patch
status: open
title: 'with' loses ->bool exceptions
type: behavior
versions: Python 2.5, Python 2.6, Python 2.7, Python 3.0, Python 3.1

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list