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()
添加回答
举报