问题描述
x = []
的正确类型提示是什么?
What is the correct type hint for x = []
?
我的 PyCharm 编辑器中的类型检查器将此标记为错误:
The type checker in my PyCharm editor flagged this as an error:
labelframes: List[ttk.LabelFrame] = []
'Optional' 不是一个选项:
'Optional' is not an option as in:
labelframes: List[Optional[ttk.LabelFrame]] = []
因为 typing.Optional
的文档说明这等效于:
because the documentation for typing.Optional
states that this is equivalent to:
labelframes: List[Union[ttk.LabelFrame, None]] = []
和 [None]
不是 []
.
我应该提到 PyCharm 也不喜欢这样:
I ought to mention that PyCharm doesn't like this either:
labelframes: List[Union[ttk.LabelFrame, None]] = [None]
无论我尝试什么类型的提示.PyCharm 将其标记为错误,希望返回我的类型提示,但没有返回,"所以我尝试了:
Whatever type hint I try. PyCharm flags it as an error with,"Expected to return my type hint here, got no return," so I tried:
labelframes: Optional[List[ttk.LabelFrame, None]] = []
那没有用.
我知道 PEP 526 有许多遵循这种模式的示例:
I am aware that PEP 526 has numerous examples which follow the pattern:
x: List[str] = []
推荐答案
查看 PEP 484,特别是 关于类型注释的部分(变量注释的前身)这确实看起来像是 PyCharm 的检查器的一个错误.
Looking at PEP 484, specifically the section on type comments (the precursor to variable annotations) this does indeed seem like a bug with PyCharm's checker.
引自 PEP:
在非存根代码中,也有类似的特例:
from typing import IO
stream = None # type: IO[str]
类型检查器不应对此抱怨(尽管值 None
与给定类型不匹配),也不应将推断类型更改为 Optional[...]
(尽管规则对默认值为 None 的带注释的参数执行此操作).这里的假设是其他代码将确保变量被赋予了正确类型的值,并且所有使用都可以假设变量具有给定类型.
Type checkers should not complain about this (despite the value None
not matching the given type), nor should they change the inferred type to Optional[...]
(despite the rule that does this for annotated arguments with a default value of None ). The assumption here is that other code will ensure that the variable is given a value of the proper type, and all uses can assume that the variable has the given type.
因此,以类似的方式,类型检查器(如 mypy
当前所做的那样)不应该抱怨您提供的初始化值与注释不严格匹配的事实.
So, in a similar fashion, type-checkers (as mypy
currently does), should not complain about the fact that the initializing value you provide doesn't strictly match the annotation.
这篇关于空列表的正确类型提示是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!