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



我的基类中有一个抽象方法,我希望所有子类都返回其预期Exception类的可迭代对象:

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()

如何键入提示此返回值?起初我想-> Iterable[Exception],但这意味着它们是Exception的实例,而不是子类。

你想要typing.Type ,它指定你返回一个类型,而不是一个实例

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

最新更新