Suppressing __context__

Antoine Pitrou solipsis at pitrou.net
Fri Oct 29 07:02:52 EDT 2010


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


Regards

Antoine.





More information about the Python-list mailing list