[Python-ideas] Arguments to exceptions

Terry Reedy tjreedy at udel.edu
Tue Jul 4 23:37:51 EDT 2017

On 7/4/2017 5:47 PM, Brendan Barnwell wrote:
> On 2017-07-04 13:54, Terry Reedy wrote:
>> There have been many proposals for what we might call RichExceptions,
>> with more easily access information.  But as Raymond Hettinger keeps
>> pointing out, Python does not use exceptions only for (hopefully rare)
>> errors.  It also uses them as signals for flow control, both as an
>> alternative form for alternation and for iteration.  Alternation with
>> try:except instead of if:else is common.  In the try: unicode example
>> above, the NameError is not an error.  Until 2.2, IndexError served the
>> role of StopIteration today, and can still be used for iteration.  For
>> flow control, richer exceptions just slow code execution.
>      How significant is this slowdown in practical terms?  Rejecting all 
> "rich" exceptions just because they might add a bit of a slowdown seems 
> premature to me.  The information available from the rich exceptions has 
> value that may or may not outweigh the performance hit.

I don't know if anyone has ever gone so far as to write a patch to test.

I personally been on the side of wanting richer exceptions.  So what has 
been the resistance?  Speed is definitely one.  Maybe space?  Probably 
maintenance cost.  Lack of interest among true 'core' (C competent) 

My suggestion for speed is that we create exception instances as fast as 
possible with the information needed to produce python values and string 
representations on demand.  Consumer pays.

This is, after all, what we often do for other builtin classes. 
Consider ints.  They have a bit length, which is an integer itself.  But 
ints do not have a Python int data attribute for that.  (If they did, 
the bit_length int would need its own bit_length attribute, and so on.) 
Instead, ints have a bit_length *method* to create a python int from 
internal data.  Ints also have a decimal string representation, but we 
do not, as far as I know, precompute it.  Ditto for the byte representation.

Terry Jan Reedy

More information about the Python-ideas mailing list