Monday, 21 September 2020

Why does raising an exception invoke __subclasscheck__?

Consider the following example that uses __subclasscheck__ for a custom exception type:

class MyMeta(type):
    def __subclasscheck__(self, subclass):
        print(f'__subclasscheck__({self!r}, {subclass!r})')

class MyError(Exception, metaclass=MyMeta):
    pass

Now when raising an exception of this type, the __subclasscheck__ method gets invoked; i.e. raise MyError() results in:

__subclasscheck__(<class '__main__.MyError'>, <class '__main__.MyError'>)
Traceback (most recent call last):
  File "test.py", line 8, in <module>
    raise MyError()
__main__.MyError

Here the first line of the output shows that __subclasscheck__ got invoked to check whether MyError is a subclass of itself, i.e. issubclass(MyError, MyError). I'd like to understand why that's necessary and how it's useful in general.


I'm using CPython 3.8.1 to reproduce this behavior. I also tried PyPy3 (3.6.9) and here __subclasscheck__ is not invoked.



from Why does raising an exception invoke __subclasscheck__?

No comments:

Post a Comment