结果" a是a是"对照

时间:2018-01-18 07:21:06

标签: python

A = 314

if A == A == A:
    print('True #1')

if A == A == 271:
    print('True #2')

lie = 0
if lie is lie is lie:
    print('no matter how white, how small,')
    print('how incorporating of a smidgeon')
    print('of truth there be in it.')

结果:

True #1
no matter how white, how small,
how incorporating of a smidgeon
of truth there be in it.

我知道在if语句中使用两个" =" s和"是不正常的。但我想知道Python解释器如何解释if语句。

表达式lie is lie is lie是同时解释还是短路?

3 个答案:

答案 0 :(得分:14)

您发生的事情称为操作员链接

来自Comparisons的文档:

  

比较可以任意链接,例如 x < y <= z   等同于x < y and y <= z ,但y仅评估一次   (但在两种情况下z都未在x < y被发现时进行评估   假)。

强调我的。

因此,这意味着lie is lie is lie被解释为(lie is lie) and (lie is lie),仅此而已。

更一般地说,a op b op c op d ...的评估方式与a op b and b op c and c op d ...相同,依此类推。表达式根据python的grammar rules进行解析。特别是;

comparison    ::=  or_expr ( comp_operator or_expr )*
comp_operator ::=  "<" | ">" | "==" | ">=" | "<=" | "!="
                   | "is" ["not"] | ["not"] "in"

答案 1 :(得分:6)

这个问题已有很多答案,但考虑将函数拆分为字节码:

def f():
    lie = 0
    if lie is lie is lie:
        print('Lie')

dis.dis(f)

  2           0 LOAD_CONST               1 (0)
              2 STORE_FAST               0 (lie)
  3           4 LOAD_FAST                0 (lie)
              6 LOAD_FAST                0 (lie)
              8 DUP_TOP
             10 ROT_THREE
             12 COMPARE_OP               8 (is)
             14 JUMP_IF_FALSE_OR_POP    22
             16 LOAD_FAST                0 (lie)
             18 COMPARE_OP               8 (is)
             20 JUMP_FORWARD             4 (to 26)
        >>   22 ROT_TWO
             24 POP_TOP
        >>   26 POP_JUMP_IF_FALSE       36
  4          28 LOAD_GLOBAL              0 (print)
             30 LOAD_CONST               2 ('Lie')
             32 CALL_FUNCTION            1
             34 POP_TOP
        >>   36 LOAD_CONST               0 (None)
             38 RETURN_VALUE

这表明正在检查所有lie以查看它们是否匹配,以线性方式。如果一个失败,它应该中断/返回。

要确认,请考虑:

>lie is lie is lie is lie is lie 
True
>lie is not lie is lie is lie is lie is lie
False
>lie is lie is lie is lie is lie is not lie
False

答案 2 :(得分:3)

它将被解释为:

lie = 0
if lie is lie and lie is lie:
    ...