PEP 409 introduced support for theraiseexcfromNone construct toallow the display of the exception context to be explicitly suppressed.This PEP retains the language level changes already implemented inPEP 409,but replaces the underlying implementation mechanism with a simpler approachbased on a new__suppress_context__ attribute on allBaseExceptioninstances.
This PEP was accepted by Alyssa Coghlan on the 14th of May, 2012.
PEP 409 changes__cause__ to beEllipsis by default. Then if__cause__ is set toNone byraiseexcfromNone, no context or causewill be printed should the exception be uncaught.
The main problem with this scheme is it complicates the role of__cause__.__cause__ should indicate the cause of the exception notwhether__context__ should be printed or not. This use of__cause__ isalso not easily extended in the future. For example, we may someday want toallow the programmer to select which of__context__ and__cause__ willbe printed. ThePEP 409 implementation is not amenable to this.
The use ofEllipsis is a hack. BeforePEP 409,Ellipsis was usedexclusively in extended slicing. Extended slicing has nothing to do withexceptions, so it’s not clear to someone inspecting an exception object why__cause__ should be set toEllipsis. UsingEllipsis by default for__cause__ makes it asymmetrical with__context__.
A new attribute onBaseException,__suppress_context__, willbe introduced. Whenever__cause__ is set,__suppress_context__will be set toTrue. In particular,raiseexcfromcausesyntax will setexc.__suppress_context__ toTrue. Exceptionprinting code will check for that attribute to determine whethercontext and cause will be printed.__cause__ will return to itsoriginal purpose and values.
There is precedence for__suppress_context__ with theprint_line_and_file exception attribute.
To summarize,raiseexcfromcause will be equivalent to:
exc.__cause__=causeraiseexc
whereexc.__cause__=cause implicitly setsexc.__suppress_context__.
There is a patch onIssue 14133.
This document has been placed in the public domain.
Source:https://github.com/python/peps/blob/main/peps/pep-0415.rst
Last modified:2025-02-01 08:59:27 GMT