More informative error messages (Re: [Python-Dev] Efficientpredicates for the standard library)

Tim Peters at
Wed Oct 8 00:02:35 EDT 2003

[Fred L. Drake, Jr.]
>> this cost was once attributed with a fairly bad performance
>> degradation when we tried a nicer message for AttributeError that
>> caused the exception instance to always be created

[Greg Ewing]
> This suggests that perhaps using exceptions for non-exceptional flow
> control isn't such a good idea, if it forces things like
> AttributeError to be less useful for debugging than they would
> otherwise be.
> I know the Python philosophy holds that you *should* be able to use
> exceptions freely for both purposes, but perhaps that philosophy needs
> to be re-examined in the light of this consideration.
> I know I find myself preferring these days to use getattr et al with
> default arguments rather than catching exceptions when testing for the
> presence of something, as it seems to more directly express what I'm
> trying to do, and avoids all chance of catching the wrong
> exception. Perhaps the equivalent should be done inside the
> interpreter, too?

The equivalent is already done inside the interpreter, about as far as is
possible.  Under the covers, the only way getattr(obj, name, default) *can*
work is to search obj's inheritance chain, trying to get the attribute at
each level, and clearing whatever internal AttributeErrors may be raised
along the way.  The presence of user-written __getattr__ hooks dooms simpler

An internal PyExc_AttributeError isn't the same as a user-visible
AttributeError, though -- a class instance isn't created unless and until
PyErr_NormalizeException() gets called because the exception needs to be
made user-visible.  If the latter never happens, setting and clearing
exceptions internally is pretty cheap (a pointer to the global
PyExc_AttributeError object is stuffed into the thread state).  OTOH, almost
every call to a C API function has to test+branch for an error-return value,
and I've often wondered whether a setjmp/longjmp-based hack might allow for
cleaner and more optimizable code (hand-rolled "real exception handling").

More information about the Python-Dev mailing list