为什么这不是python中的语法错误? [英] Why isn't this a syntax error in python?

查看:73
本文介绍了为什么这不是python中的语法错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天在我们的代码库中删了一行,我认为肯定会因语法错误而使构建失败,但是测试通过了,显然它实际上是有效的python(在2.x和3中)。



有时在条件表达式中不需要空格:

 > ;>> 1如果是,否则为0 
1

如果LHS是变量,则不起作用:

 >> x = 1 
>> xif True else 0
文件< stdin>,第1行
xif True else 0
^
SyntaxError:语法无效

但它似乎仍然可以与其他类型的文字一起使用:

 >> {'hello'}如果为false,则为'potato'
'potato'

在这里,出于某种原因,它是否有意成为语法的一部分?

解决方案


令牌之间的空白



在逻辑行的开头或字符串文字中,可以互换使用空格字符空格,制表符和换页符来分隔标记。仅当两个令牌之间的级联可以被解释为其他令牌(例如,ab是一个令牌,而ab是两个令牌)时,才需要在两个令牌之间使用空格。


因此,在这种情况下, 1if 不是有效的令牌,因此空白是可选的。 1 被解释为整数文字,而 if 不是其中的一部分。因此 if 会被单独解释并识别为关键字。



xif ,但是会识别出一个标识符,因此Python无法看到您要在 x $ c

Noticed a line in our codebase today which I thought surely would have failed the build with syntax error, but tests were passing so apparently it was actually valid python (in both 2.x and 3).

Whitespace is sometimes not required in the conditional expression:

>>> 1if True else 0
1

It doesn't work if the LHS is a variable:

>>> x = 1
>>> xif True else 0
  File "<stdin>", line 1
    xif True else 0
           ^
SyntaxError: invalid syntax

But it does seem to still work with other types of literals:

>>> {'hello'}if False else 'potato'
'potato'

What's going on here, is it intentionally part of the grammar for some reason? Is this odd quirk a known/documented behaviour?

解决方案

Whitespace between tokens

Except at the beginning of a logical line or in string literals, the whitespace characters space, tab and formfeed can be used interchangeably to separate tokens. Whitespace is needed between two tokens only if their concatenation could otherwise be interpreted as a different token (e.g., ab is one token, but a b is two tokens).

So in this case, 1if is not a valid token, so the whitespace is optional. The 1 is interpreted as an integer literal of which the if is not a part. So if is interpreted separately and recognized as a keyword.

In xif however, an identifier is recognized, so Python is not able to see that you wanted to do x if there.

这篇关于为什么这不是python中的语法错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆