How to type hint a return value of Exception's subclass?

Mar*_*nen 3 python type-hinting python-3.x python-typing

I have an abstract method in my base class, and I want all the subclasses to return an iterable of their expected Exception classes:

class Foo(metaclass=ABCMeta):
    @abstractmethod
    def expected_exceptions(self):
        raise NotImplementedError()

class Bar(Foo):
    def expected_exceptions(self):
        return ValueError, IndexError

class Baz(Foo):
    def expected_exceptions(self):
        yield from self.manager._get_exceptions()
Run Code Online (Sandbox Code Playgroud)

How do I type hint this return value? At first I thought of -> Iterable[Exception], but that would mean they are instances of Exception, as opposed to subclasses.

gmd*_*mds 5

您需要typing.Type,它指定您要返回的是类型,而不是实例

from typing import Type, Iterable

def expected_exceptions(self) -> Iterable[Type[Exception]]:
    return ValueError, IndexError
Run Code Online (Sandbox Code Playgroud)