首页 > 解决方案 > 当省略 if 后的空格时,为什么 python3 内联 if 语句不会引发 SyntaxError?

问题描述

Python 3.6 和最高版本 3.8 中的以下语句不会引发 SyntaxError,Python 2.7 和 Python 3.5 会这样做。

>>> ifNone: print(5)
5

>>> ifTrue: print('a')
a

>>> ifnotNone: print('foo')
foo

另请注意,在执行 print 语句之前不显示省略号。通常内联 if 语句具有以下结构。

>>> if True: print('bar')
...
bar

>>> if False: print(10)
...
>>>

什么允许这种行为?

标签: pythonif-statementpython-3.6

解决方案


第一个示例可能是声明一个名为 ifNone 的变量为 print(5) 类型。

回想一下 PEP484 和 PEP526 类型注释只是对 Python 解释器的注释;你需要像 mypy 这样的东西来理解它们。


推荐阅读