Current documentation says:

"An object is compatible with an exception if it is the class or a base class of the exception object or a tuple containing an item compatible with the exception."

https://docs.python.org/3/reference/compound_stmts.html#the-try-statement

It is, in my opinion, not very clear from this that the __instancecheck__ mechanism is bypassed.

Should the documentation perhaps be adapted to explain that the class needs to actually occur in the MRO
and that virtual base classes are not considered for matching purposes?

"An object is compatible with an exception if it is the class or a non-virtual base class of the exception object or a tuple containing an item compatible with the exception.
The exception matching machinery ignores the __instancecheck__ mechanism."


Stephan


2018-05-31 9:19 GMT+02:00 Terry Reedy <tjreedy@udel.edu>:
On 5/31/2018 12:47 AM, Danilo J. S. Bellini wrote:
Hi!
I was working on handling some exceptions from external software
(e.g. database constraint triggers)
switching the handler based on the messages that had been sent.
Today we can do something like (running on Python 3.6.5):


try:
...     # [...]
...     session.commit() # Here it raises!
...     # [...]
... except DatabaseError as exc:
...     msg = get_db_error_msg_from_exception(exc)
...     if msg == "beyond_limit":
...         # [...]
...     elif msg == "no_funds":
...         # [...]
...     else:
...         raise


That works,

Yes, it works perfectly well, AND it exposes the fact that your code depends on the message, which I think is a good thing.

As Stephen said, messages are intentionally not part of the defined API.  As a matter of curtesy, we usually restrict message changes to new versions and do not backport the change. An exception may be made if we decide that a message is sufficiently erroneous that is likely misleads people.  In any case, message dependent code may be version dependent.

--
Terry Jan Reedy



_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/