以下代码存储在名为
示例.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
mypython 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()
可以返回
None
类型,它没有
groups
属性,将处理结果异常并在返回类型中指定处理。但是,Mypy似乎不理解异常正在被处理。据我所知
Optional[Tuple[str, str]]
是正确的返回类型,而Mypy坚持认为
Union[Sequence[str], Any]
是正确的。对Python类型使用异常处理的正确方法是什么?(请注意,我并没有要求在不使用异常处理的情况下使用其他方法来编写代码。我只是想提供一个简单而完整的示例,其中Python类型的checker的行为与异常处理的预期不同。)