亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 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 關注
  • 128 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號