【问题标题】:Why doesn't Python always require spaces around keywords?为什么 Python 不总是要求关键字周围有空格?
【发布时间】:2023-03-13 03:20:02
【问题描述】:

为什么有时可以在关键字前后省略空格?例如,为什么表达式2if-1e1else 1 有效?

似乎在 CPython 2.7 和 3.3 中都可以使用:

$ python2
Python 2.7.3 (default, Nov 12 2012, 09:50:25) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 2if-1e1else 1
2

$ python3
Python 3.3.0 (default, Nov 12 2012, 10:01:55) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 2if-1e1else 1
2

甚至在 PyPy 中:

$ pypy
Python 2.7.2 (341e1e3821ff, Jun 07 2012, 15:42:54)
[PyPy 1.9.0 with GCC 4.2.1] on darwin
Type "help", "copyright", "credits" or "license" for more information.
And now for something completely different: ``PyPy 1.6 released!''
>>>> 2if-1e1else 1
2

【问题讨论】:

  • 开始看起来像 perl

标签: python pypy cpython


【解决方案1】:

python中的标识符描述为:

identifier ::= (letter|"_") (letter | digit | "_")* 

因此,2if 不能是标识符,因此 if 必须是 2,if。类似的逻辑适用于表达式的其余部分。

基本上解释2if-1e1else 1 会是这样(完整的解析会相当复杂):

2if 无效标识符,2 匹配数字 digit ::= "0"..."9",if 匹配关键字。 -1e1else, -1: 的一元否定 (u_expr ::= power | "-" u_expr | "+" u_expr | "~" u_expr) (1 匹配 intpart in exponentfloat ::= (intpart | pointfloat) | exponent , e1 是指数 exponent ::= ("e" | "E") ["+" | "-"] digit+。)你可以看到 Ne+|-x 形式的表达式产生一个浮点数:

>>> type(2e3)
<type 'float'>

然后else 被视为关键字,-1 等。

您可以细读gammar 以了解更多信息。

【讨论】:

  • "...-1 匹配 intpart..." 等等,什么? - 不是一元运算符吗?
  • 所以基本上就是这样,因为阻止它会使语法/解析器更加复杂。
  • @asmeurer 是这样的,因为它语法(如果有意义的话)
  • 嗯,呃,但我很确定语法不是自己写的。 Python 语言的每个方面都是有原因的。
  • 为了额外的乐趣:在表达式中使用2if 是可以接受的,但使用2else 是不行的;这可能是因为后者被解析为2e?????? 是一个非数字,这是一个语法错误。
猜你喜欢
  • 2014-02-06
  • 1970-01-01
  • 2022-10-15
  • 1970-01-01
  • 1970-01-01
  • 2019-04-17
相关资源
最近更新 更多