[issue6210] Exception Chaining missing method for suppressing context

Nick Coghlan report at bugs.python.org
Sat Dec 4 18:18:16 CET 2010


Nick Coghlan <ncoghlan at gmail.com> added the comment:

To get back to my original objection, it shouldn't be that difficult to differentiate between "__context__ never set" and "__context__ explicitly suppressed".

(e.g. using a property that sets an internal flag when set from Python code or via PyObject_SetAttr, or else a special ExceptionContextSuppressed singleton).

BaseException could then be given a "no_context" class method that did whatever dancing was necessary to suppress the context.

So Steven's examples would become:
def process(iterable):
    try:
        x = next(iterable)
    except StopIteration:
        raise ValueError.no_context("can't process empty iterable")
    continue_processing()

def func(x):
    try:
        x + 0
    except (ValueError, TypeError):
        raise MyException.no_context('x is not a number')
    do_something_with(x)

With appropriate changes to the exception display code, no_context could be as simple as the C equivalent of the following:

@classmethod
def no_context(cls, *args, **kwds):
  exc = cls(*args, **kwds)
  exc.__context__ = ExceptionContextSuppressed
  return exc

Another alternative would be an additional internal flag queried by the exception chaining code itself:

@classmethod
def no_context(cls, *args, **kwds):
  exc = cls(*args, **kwds)
  exc.__context__ = None
  exc._add_context = False
  return exc

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue6210>
_______________________________________


More information about the Python-bugs-list mailing list