Associativity of “in” in Python?

后端 未结 4 727
既然无缘
既然无缘 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 15:57

    1 in [] in 'a' is evaluated as (1 in []) and ([] in 'a').

    Since the first condition (1 in []) is False, the whole condition is evaluated as False; ([] in 'a') is never actually evaluated, so no error is raised.

    Here are the statement definitions:

    In [121]: def func():
       .....:     return 1 in [] in 'a'
       .....: 
    
    In [122]: dis.dis(func)
      2           0 LOAD_CONST               1 (1)
                  3 BUILD_LIST               0
                  6 DUP_TOP             
                  7 ROT_THREE           
                  8 COMPARE_OP               6 (in)
                 11 JUMP_IF_FALSE            8 (to 22)  #if first comparison is wrong 
                                                        #then jump to 22, 
                 14 POP_TOP             
                 15 LOAD_CONST               2 ('a')
                 18 COMPARE_OP               6 (in)     #this is never executed, so no Error
                 21 RETURN_VALUE         
            >>   22 ROT_TWO             
                 23 POP_TOP             
                 24 RETURN_VALUE        
    
    In [150]: def func1():
       .....:     return (1 in  []) in 'a'
       .....: 
    
    In [151]: dis.dis(func1)
      2           0 LOAD_CONST               1 (1)
                  3 LOAD_CONST               3 (())
                  6 COMPARE_OP               6 (in)   # perform 1 in []
                  9 LOAD_CONST               2 ('a')  # now load 'a'
                 12 COMPARE_OP               6 (in)   # compare result of (1 in []) with 'a'
                                                      # throws Error coz (False in 'a') is
                                                      # TypeError
                 15 RETURN_VALUE   
    
    
    
    In [153]: def func2():
       .....:     return 1 in ([] in 'a')
       .....: 
    
    In [154]: dis.dis(func2)
      2           0 LOAD_CONST               1 (1)
                  3 BUILD_LIST               0
                  6 LOAD_CONST               2 ('a') 
                  9 COMPARE_OP               6 (in)  # perform ([] in 'a'), which is 
                                                     # Incorrect, so it throws TypeError
                 12 COMPARE_OP               6 (in)  # if no Error then 
                                                     # compare 1 with the result of ([] in 'a')
                 15 RETURN_VALUE        
    

提交回复
热议问题