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

标签 python python-3.x type-hinting python-typing

我的基类中有一个抽象方法,我希望所有子类都返回它们预期的 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

关于python - 如何键入提示异常子类的返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56336702/

相关文章:

python - 为什么我的正则表达式与我需要的电话号码不匹配?

Python:从时间戳中添加或删除时区小时并获取实际时间

python - 带有键/值类型对的类型提示字典

python - 如何循环保存PIL图像

python - django 和 csrf_token 问题

python - Pandas : Aggregated and Group by - IDE: Pycharm

python - 为什么 mypy 找不到我的包裹?

python - 输入提示和@singledispatch : how do I include `Union[...]` in an extensible way?

python - 提交 Flask WTForms 时,如何将字段留空而不从数据库表中删除这些值?

python - 在 Python 中识别视觉上相似的字符串