我有以下Python代码:
from pathlib import Path
def ffind_overview_ex(base_dir: Path, exc: Exception = FileNotFoundError) -> Path:
try:
# do something
except Exception as err:
raise exc("hello") from err
## do some more
if some_extraordinary_condition:
raise exc("Wow, it really happened!?")
return result # result is of type Path
test = foo(SystemExit)
代码工作得很好,但是 MyPy 对此代码很生气:
lib\cnmerge\merger.py:53: error: Incompatible default for argument "exc" (default has type "type[FileNotFoundError]", argument has type "Exception") [assignment]
lib\cnmerge\merger.py:59: error: "Exception" not callable [operator]
lib\cnmerge\merger.py:62: error: "Exception" not callable [operator]
lib\cnmerge\merger.py:67: error: "Exception" not callable [operator]
test.py:96: error: Argument 2 to "ffind_overview_ex" has incompatible type "type[SystemExit]"; expected "Exception" [arg-type]
Found 5 errors in 2 files (checked 1 source file)
我的目的是控制 ffind_overview_ex() 抛出的异常类型,而不是创建一个复杂的 except 块来处理 ffind_overview_ex() 可能抛出的无数异常,或者创建一个接收器异常处理程序。
那么,当代码可以运行时,MyPy 该怎么办?怎样才能“安抚”它呢? AFAIK FileNotFoundError 和 SystemExit 都是从 Exception 继承的。