Python grammar有这样的规则:
assignment:
| NAME ':' expression ['=' annotated_rhs ]
# other options for rule omitted
而表达式
规则允许lambda定义(lambdef
)。
这意味着这个 python 语法是有效的:
q: lambda p: p * 4 = 1
是否存在允许 lambda 存在的用例,或者这只是某种松散语法的怪癖?同样,这允许条件类型 a: int if b > 3 else str = quux
,这看起来更理智一些,但仍然出人意料。
最佳答案
这是在 PEP-0526(Syntax for Variable Annotations) 下指定的。 Python 不关心注释,只要“它评估而不引发”。类型检查器的职责是将其标记为无效注释。
引自政治公众人物:
Other uses of annotations
While Python with this PEP will not object to:
alice: 'well done' = 'A+'
bob: 'what a shame' = 'F-'
since it will not care about the type annotation beyond “it evaluates without raising”, a type checker that encounters it will flag it, unless disabled with
#type: ignore
or@no_type_check
.However, since Python won’t care what the “type” is, if the above snippet is at the global level or in a class,
__annotations__
will include{'alice': 'well done', 'bob': 'what a shame'}
.These stored annotations might be used for other purposes, but with this PEP we explicitly recommend type hinting as the preferred use of annotations.
例如,使用 mypy
运行代码片段将产生以下错误:
file.py:1: error: Invalid type comment or annotation [valid-type]
关于python - 为什么允许 `lambdef` 作为变量的类型提示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77272655/