【发布时间】:2019-07-19 19:58:02
【问题描述】:
以下代码存储在一个名为 sample.py 的文件中。
import re
from typing import Optional, Tuple
def func(path: str) -> Optional[Tuple[str, str]]:
regex = re.compile(r"/'([^/']+?)'/'([^/']+?)'")
try:
return regex.match(path).groups()
except AttributeError:
return None
Mypy Python linter 在分析代码时抛出以下错误:
sample.py:8: error: Incompatible return value type (got "Union[Sequence[str], Any]", expected "Optional[Tuple[str, str]]")
sample.py:8: error: Item "None" of "Optional[Match[str]]" has no attribute "groups"
虽然regex.match(path).groups() 可能返回没有groups 属性的None 类型,但会处理生成的异常并在返回类型中指定处理。但是,Mypy 似乎不明白正在处理异常。据我了解 Optional[Tuple[str, str]] 是正确的返回类型,而 Mypy 坚持认为不太具体的类型 Union[Sequence[str], Any] 是正确的。在 Python 类型中使用异常处理的正确方法是什么? (请注意,我并不是要求在不使用异常处理的情况下编写代码的替代方法。我只是想提供一个最小且完整的示例,其中 Python 类型检查器的行为与我对异常处理的预期不同。)
【问题讨论】:
标签: python-3.x exception type-hinting mypy