python - 当我提前返回值为 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")
and note: Left operand is of type "Optional[List[str]]"
for 这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
推荐阅读
- django - 如何在 django models.py 中编写一个使用定义的函数?
- mysql - 如何获取最近 7 天的数据
- java - 无法获取设备 IMEI
- angular - Angular 自定义表单控件 - 获取默认值
- kibana - 如何在kibana中设置keycloak认证
- ios - 何时更新 tableView?
- google-bigquery - GoolgeBigQuery - 超出速率限制
- python-3.x - 为什么矩形选择器不能在绘图内移动
- python - 在过滤数据框(census.csv)中的多列时提取前 3 个值
- dom - 更新 SVG 元素的转换时,Firefox 会移动剪辑路径,而 Chromium 不会 - 这是正确的,什么是可移植的解决方案?