Suppressing __context__

Antoine Pitrou solipsis at pitrou.net
Fri Oct 29 07:59:46 EDT 2010


On Fri, 29 Oct 2010 04:07:15 -0700
Chris Rebert <clp2 at rebertia.com> wrote:

> On Fri, Oct 29, 2010 at 4:02 AM, Antoine Pitrou <solipsis at pitrou.net> wrote:
> > On Sun, 24 Oct 2010 10:48:23 +0200
> > "Martin v. Loewis" <martin at v.loewis.de> wrote:
> >>
> >> You may now wonder whether it is possible to set __context__ to None
> >> somehow. See PEP 3134:
> >>
> >> Open Issue: Suppressing Context
> >>
> >>     As written, this PEP makes it impossible to suppress '__context__',
> >>     since setting exc.__context__ to None in an 'except' or 'finally'
> >>     clause will only result in it being set again when exc is raised.
> >
> > It is not easily discoverable, but it is possible to suppress
> > __context__ by using a bare re-raise afterwards:
> >
> >>>> try:
> > ...   try: 1/0
> > ...   except ZeroDivisionError: raise KeyError
> > ... except BaseException as e:
> > ...   e.__context__ = None
> > ...   raise
> > ...
> > Traceback (most recent call last):
> >  File "<stdin>", line 3, in <module>
> > KeyError
> 
> So, how/why does that work?

A bare "raise" simply re-raises the currently known exception without
changing anything (neither the traceback nor the context).

This __context__ problem is mostly theoretical, anyway. If you want to
present exceptions to users in a different way, you can write a
catch-all except clause at the root of your program and use the
traceback module to do what you want.

Regards

Antoine.



More information about the Python-list mailing list