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()
添加回答
舉報