python - 为什么允许 `lambdef` 作为变量的类型提示?

标签 python python-3.x grammar

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/

相关文章:

python - 使用 Falcon REST API 提供 pdf 文件

python - 从字符串 NLP 中删除英语 "crap"单词的策略,例如 "um"、 "uh"

javascript - 如何使用Python登录网页?

python - 从列表创建组合而不考虑相邻元素

python - 如何为新标签设置页面加载超时

grammar - 有 Perl6 规范形式吗?

C++ 为什么在我的类中添加析构函数会使我的类无法 move ?

haskell - haskell中的递归数据结构: prolog-like terms

python - 将值插入列表中所有可能的位置

python-3.x - 在flask中创建评论部分