Associativity of “in” in Python?

后端 未结 4 725
既然无缘
既然无缘 2021-01-30 15:15

I\'m making a Python parser, and this is really confusing me:

>>>  1 in  []  in \'a\'
False

>>> (1 in  []) in \'a\'
TypeError: \'in &         


        
4条回答
  •  [愿得一人]
    2021-01-30 16:14

    From the documentation:

    Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

    What this means is, that there no associativity in x in y in z!

    The following are equivalent:

    1 in  []  in 'a'
    # <=>
    middle = []
    #            False          not evaluated
    result = (1 in middle) and (middle in 'a')
    
    
    (1 in  []) in 'a'
    # <=>
    lhs = (1 in []) # False
    result = lhs in 'a' # False in 'a' - TypeError
    
    
    1 in  ([] in 'a')
    # <=>
    rhs = ([] in 'a') # TypeError
    result = 1 in rhs
    

提交回复
热议问题