python - MyPy - 赋值中不兼容的类型(表达式的类型为 None,变量的类型为 X)
问题描述
有谁知道为什么 MyPy 抱怨这个?这是非常令人沮丧的,因为如果它是三元的,但如果在标准的 if/else 中,它就不起作用:
from typing import List, Optional, Union
def get_relevant_params() -> List[str]:
return sorted(list(set(['1', '2', '3'])))
# also doesn't work with: ... -> Union[List[str], None]
def get_config(config_path: Optional[str] = None) -> Optional[List[str]]:
# this doesn't work
if config_path:
read_cols = get_relevant_params()
else:
read_cols = None
# # this works
# read_cols = get_relevant_params() if config_path else None
return read_cols
这是一个带有示例的交互式 MyPy 游乐场: https ://mypy-play.net/?mypy=latest&python=3.8&gist=2c846e569ecbd5f8884367393a754adc
解决方案
将第 11 行更改为:
read_cols: Optional[List[str]] = get_relevant_params()
您的问题是 mypy 将变量的类型read_cols
自动识别为 List[str] 因为那是get_relevant_params
. 然后,当您尝试将 None 分配给它时,它会显示“不兼容的类型”。如果您在创建变量时指定您希望它是可选的,那么一切正常。
也许更清洁的解决方案是避免使用返回变量。
if config_path:
return get_relevant_params()
else:
return None
这样,就不会对config_path
.
推荐阅读
- c# - 如何从字符串中检索多个空格
- django - Django AUTH_USER_MODEL 引用了尚未安装的模型“%s”
- apostrophe-cms - 如何允许删除撇号数组对象中的数组项
- amazon-web-services - Kinesis 和 DynamoDB 事件源的不同 AWS 故障处理功能如何交互?
- python - Python将元素列表附加到空数据框的一行
- tensorflow-federated - TFF:模拟用户的随机样本时准确性没有增加
- mysql - 如何转置 MySQL 动态 SELECT 语句
- reactjs - useState 变量未在 chrome 调试器中更新,但已在 ReactDevTools 中更新
- c++ - 使用 gdiplus 绘制叠加层
- laravel - 如何使用 Laravel 仅显示特定用户的数据