Python is, == operator precedence

后端 未结 2 2011

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:01

    According to the documentation, all python comparisons operators has same priority:

    There are eight comparison operations in Python. They all have the same priority (which is higher than that of the Boolean operations).

    However by wrapping comparisons with the brackets, they start to be the atoms expressions, so statements in brackets evaluated before statements outside, that impacts the order of the evalutation, I will decompose the first "contradictional" case, the all others is similar:

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

    Per documentation the priority is the same, so evaluation is next:

    1. a is None ? -> False # Because a == 3
    2. False == b -> False # Because b == 3
    3. False is None
    

    Please see order for the second case below:

    (a is None) == (b is None)
    
    1. a is None ? -> False # Because a == 3
    2. b is None -> False # Because b == 3
    3. False is False -> True
    

提交回复
热议问题