The Python documentation for except
says:
For an except clause with an expression, that expression is evaluated, and the clause matches the exception if the resulting object is “compatible” with the exception. An object is compatible with an exception if it is the class or a base class of the exception object, [...]
Why doesn't except
use isinstance
instead of comparing base classes? This is preventing the use of __instancecheck__
to override the instance check.
EDIT:
I can understand that one of the reasons this doesn't exist is that no one considered it. But are there any reasons why this should not be implemented?
EDIT:
Shell session from Python 3.2a showing that trying to use __subclasscheck__
for this doesn't work:
>>> class MyType(type): __subclasscheck__ = lambda cls, other_cls: True
>>> class O(Exception, metaclass=MyType): pass
>>> issubclass(3, O)
0: True
>>> issubclass(int, O)
1: True
>>> try:
... 1/0
... except O:
... print('Success')
Traceback (most recent call last):
File "<pyshell#4>", line 2, in <module>
1/0
ZeroDivisionError: division by zero
>>>