如何解决当我在值为 None 时提前返回时,为什么我会收到 Optional 类型的 mypy 错误?
如果我在使用 mypy 时遇到错误,我将不胜感激。
我的函数看起来像:
def get_result(
f1: float,l: List[float],d: Dict[float,Optional[List[str]]],f2: float,s: str
) -> Optional[List[str]]:
if f1 is in l:
if d[f2] is None:
return [s]
else:
return sorted(d[f2] + [s])
return d[f2]
然而,mypy 为 error: Unsupported left operand type for + ("None")
行提供了 note: Left operand is of type "Optional[List[str]]"
和 return sorted(d[f2] + [s])
,即使我在值为 None 时提前返回。
非常感谢任何帮助。
解决方法
我的理解是 Mypy 不够聪明,无法记住字典的特定项目在 is None
或 isinstance
检查后具有特定类型。如果您直接为该项目命名,它可以记住这些事情。在您的示例中:
def get_result(
f1: float,l: List[float],d: Dict[float,Optional[List[str]]],f2: float,s: str
) -> Optional[List[str]]:
# explicitly name the item that we care about
d_f2 = d[f2]
if f1 is in l:
# use the given name directly
if d_f2 is None:
return [s]
else:
return sorted(d_f2 + [s])
return d_f2
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。