[Python-ideas] Arguments to exceptions

Kyle Lahnakoski klahnakoski at mozilla.com
Wed Jul 5 12:47:42 EDT 2017


I agree with Ken for the need to make rich exceptions easy to write, but
I do not know enough to say if changing BaseException to support this is
a good idea; I made my own error reporting library to do this: For
example, to define a new exception type with a `name` attribute:

raise Log.error("name {{name|quote}} is not defined.", name=name)

My point is that the first parameter, the template string, acts as the
class definition.

Now, there are some extra "features": The mustaches demand named
parameters, and use pipe for some simple formatting hints; I hope you
can overlook that and maybe use f-strings, or similar. The template
string is not expanded unless the text log is required; the errors
serialize nicely to JSON for a structured logging system; querying for
instances of this error is the same as looking for the template string.

My library does not solve the problem of extracting parameters out of
the standard lib errors; but catching them early, chaining, and properly
classing them, is good enough.

    >>> try:
    ...     a={}  # imagine this is something complicated
    ...     c = a.b
    ... except Exception as e:
    ...     Log.error("can not do something complicated", cause=e)  # just like raise from, plus we are defining a new exception type


On 2017-07-05 00:21, Terry Reedy wrote:
> On 7/4/2017 6:31 PM, Greg Ewing wrote:
>> Terry Reedy wrote:
>>> Attaching a *constant* string is very fast, to the consternation of
>>> people who would like the index reported.
>
> Actually, the constant string should be attached to the class, so
> there is no time needed.
>
>> Seems to me that storing the index as an attribute would help
>> with this. It shouldn't be much slower than storing a constant
>> string,
>
> Given that the offending int is available as a Python int, then
> storing a reference should be quick, though slower than 0  (see above
> ;-).
>
>> and formatting the message would be deferred until
>> it's needed, if at all.
>
> I agree that this would be the way to do it.  I will let an advocate
> of this enhancement lookup the rejected issue (there may be more than
> one) proposing to make the bad index available and see if this is the
> actual proposal rejected and if so, why (better than I may remember).
>
> It occurs to me that if the exception object has no reference to any
> python object, then all would be identical and only one cached
> instance should be needed.  I checked and neither IndexError nor
> ZeroDivisionError do this.
>




More information about the Python-ideas mailing list