【发布时间】:2018-01-01 16:04:51
【问题描述】:
尝试在 Python 代码中使用静态类型,所以mypy 可以帮助我解决一些隐藏的错误。使用单个变量非常简单
real_hour: int = lower_hour + hour_iterator
列表和字典更难使用,需要导入额外的typing库:
from typing import Dict, List
hour_dict: Dict[str, str] = {"test_key": "test_value"}
但主要问题 - 如何将它与具有不同值类型的字典一起使用,例如:
hour_dict = {"test_key": "test_value", "test_keywords": ["test_1","test_2"]}
如果我不对此类字典使用静态类型 - mypy 会显示错误,例如:
len(hour_dict['test_keywords'])
- Argument 1 to "len" has incompatible type
那么,我的问题是:如何将静态类型添加到此类字典中? :)
【问题讨论】:
-
如果 dict 可以包含的所有类型都是已知的,您可以使用
Union。例如Dict[str, Union[list, str]]。但是,这并不能确保特定的键始终是指定的类型,它只允许值是(例如)字符串或列表。 -
(另外,它是
Dict[str, str],而不是Dict[str:str]。)
标签: python python-3.x static-typing mypy