Python is, == operator precedence

后端 未结 2 2028

In Python3,

a = b = 3
a is None == b is None

returns False, but

(a is None) == (b is None)

returns True.

2条回答
  •  不要未来只要你来
    2021-01-07 23:17

    What you see here is operator chaining and there is no precedence involved at all!

    Python supports expressions like

    1 < a < 3
    

    To test that a number is in between 1 and 3; it's equal to (1 < a) and (a < 3) except that a is only evaluated once.

    Unfortunately that also means that e.g.

    None is None == None
    

    actually means

    (None is None) and (None == None)
    

    which is of course True, and the longer example you started with

    a = b = 3
    a is None == b is None
    

    means

    (a is None) and (None == b) and (b is None)
    

    which can only be True if both a and b are None.

    Documentation here, see the bit about chaining.

    Very useful sometimes but it also pops up when you least expect it!

提交回复
热议问题