第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

使用 mypy 時在 python 中正確鍵入異常/錯誤元組

使用 mypy 時在 python 中正確鍵入異常/錯誤元組

小唯快跑啊 2022-10-18 14:45:52
我編寫了自己的裝飾器add_warning,以便在發(fā)生某些錯誤時打印成本錯誤消息。裝飾器接收一條消息以及打印該消息的錯誤類型。我還想在這個裝飾器中添加類型并使用mypy. 這Exception在我使用Type[Exception]. 但是,mypy當(dāng)我使用其他錯誤時抱怨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貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超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()


查看完整回答
反對 回復(fù) 2022-10-18
  • 1 回答
  • 0 關(guān)注
  • 131 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號