为了账号安全,请及时绑定邮箱和手机立即绑定

使用 mypy 时在 python 中正确键入异常/错误元组

使用 mypy 时在 python 中正确键入异常/错误元组

小唯快跑啊 2022-10-18 14:45:52
我编写了自己的装饰器add_warning,以便在发生某些错误时打印成本错误消息。装饰器接收一条消息以及打印该消息的错误类型。我还想在这个装饰器中添加类型并使用mypy. 这Exception在我使用Type[Exception]. 但是,mypy当我使用其他错误时抱怨OSError或AttributeError说:error: Argument "errors" to "add_warning" has incompatible type "Tuple[Type[OSError], Type[AttributeError]]"; expected "Union[str, Type[Exception], Tuple[Type[Any]]]".有谁知道是否有比使用Any或Tuple[Type[OSError], Type[AttributeError]]这里更好的方法?具体来说,是否所有 Python 错误都有更通用的类型?下面是代码:from functools import wrapsfrom typing import Union, Tuple, Callable, Typedef add_warning(message: str, flag: str = 'Info',                errors: Union[str, Type[Exception], Tuple[Type[Exception]]] = 'all') -> Callable:    """    Add a warning message to a function, when certain error types occur.    """    if errors == 'all':        errors = Exception    def decorate(func: Callable):        @wraps(func)        def wrapper(*args, **kwargs):            try:                result = func(*args, **kwargs)            except errors:                warn(message, flag)                return []            else:                return result        return wrapper    return decoratedef warn(message: str, flag: str = 'Info') -> None:    """Print the colored warning message."""    print(f"{flag}: {message}")if __name__ == '__main__':    @add_warning('This is another test warning.', flag='Error')    def test_func1():        raise Exception    @add_warning('This is a test warning.', flag='Error', errors=(OSError, AttributeError))    def test_func2():        raise OSError    test_func1()    test_func2()
查看完整描述

1 回答

?
繁花不似锦

TA贡献1851条经验 获得超4个赞

问题是这Tuple[Type[Exception]意味着一个具有单个值的元组。你想要一个可变大小的元组,所以使用省略号:Tuple[Type[Exception], ...]以下工作没有 mypy 抱怨:


from functools import wraps

from typing import Union, Tuple, Callable, Type



def add_warning(message: str, flag: str = 'Info',

                errors: Union[str, Type[Exception], Tuple[Type[Exception], ...]] = 'all') -> Callable:

    """

    Add a warning message to a function, when certain error types occur.

    """

    if errors == 'all':

        errors = Exception


    def decorate(func: Callable):

        @wraps(func)

        def wrapper(*args, **kwargs):

            try:

                result = func(*args, **kwargs)

            except errors:

                warn(message, flag)

                return []

            else:

                return result

        return wrapper

    return decorate



def warn(message: str, flag: str = 'Info') -> None:

    """Print the colored warning message."""

    print(f"{flag}: {message}")



if __name__ == '__main__':


    @add_warning('This is another test warning.', flag='Error')

    def test_func1():

        raise Exception


    @add_warning('This is a test warning.', flag='Error', errors=(OSError, AttributeError))

    def test_func2():

        raise OSError


    test_func1()

    test_func2()


查看完整回答
反对 回复 2022-10-18
  • 1 回答
  • 0 关注
  • 116 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号