如何键入异常子类的 return 值提示?

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

我的基础 class 中有一个抽象方法,我希望所有的子class 都是 return 他们期望的可迭代 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()

如何键入提示此 return 值?起初我想到了 -> Iterable[Exception],但这意味着它们是 Exception 的实例,而不是 subclasses.

你想要 typing.Type,它指定你要返回一个 type,而不是 instance:

from typing import Type, Iterable

def expected_exceptions(self) -> Iterable[Type[Exception]]:
    return ValueError, IndexError