[Python-ideas] Arguments to exceptions

Steven D'Aprano steve at pearwood.info
Tue Jul 4 10:10:26 EDT 2017


On Mon, Jul 03, 2017 at 06:29:05AM -0400, Juancarlo Añez wrote:
> On Mon, Jul 3, 2017 at 4:59 AM, Ken Kundert <python-ideas at shalmirane.com>
> wrote:
> 
> > That is the problem.  To write the error handler, I need the misspelled
> > name.
> > The only way to get it is to extract it from the error message. The need to
> > unpack information that was just packed suggests that the packing was done
> > too
> > early.  That is my point.
> >
> 
> 
>    1. You can pass an object with all the required information and an
>    appropriate __str__() method to the exception constructor.

Playing Devil's Advocate, or in this case, Ken's Advocate, I don't think 
that's a useful approach. Think of it from the perspective of the 
caller, who catches the exception. They have no way of forcing the 
callee (the code being called) to use that custom object with the 
appropriate __str__ method, so they can't rely on it:

try:
    something()
except NameError as err:
    msg = err.args[0]
    if hasattr(msg, 'name'):
        name = msg.name
    else:
        # extract using a regex or similar...
        name = ...

which doesn't seem very friendly. And who says that this custom object 
with a custom __str__ actually uses 'name' as part of its API? I might 
be extracting a completely different attribute unrelated to the failed 
name lookup.

I think Ken is right that *if* this problem is worth solving, we should 
solve it in BaseException (or at least StandardException), and not leave 
it up to individual users to write their own mutually incompatible APIs 
for extracting the name from NameError.



-- 
Steve


More information about the Python-ideas mailing list