python operator, no operator for “not in”

后端 未结 2 1524
长发绾君心
长发绾君心 2020-12-11 00:55

This is a possibly silly question, but looking at the mapping of operators to functions I noticed that there is no function to express the not in operator. At

相关标签:
2条回答
  • 2020-12-11 01:15

    Another function is not necessary here. not in is the inverse of in, so you have the following mappings:

    obj in seq => contains(seq, obj)
    
    obj not in seq => not contains(seq, obj)
    

    You are right this is not consistent with is/is not, since identity tests should be symmetrical. This might be a design artifact.

    0 讨论(0)
  • 2020-12-11 01:29

    You may find the following function and disassembly to be helpful for understanding the operators:

    >>> def test():
            if 0 in (): pass
            if 0 not in (): pass
            if 0 is (): pass
            if 0 is not (): pass
            return None
    
    >>> dis.dis(test)
      2           0 LOAD_CONST               1 (0) 
                  3 LOAD_CONST               2 (()) 
                  6 COMPARE_OP               6 (in) 
                  9 POP_JUMP_IF_FALSE       15 
                 12 JUMP_FORWARD             0 (to 15) 
    
      3     >>   15 LOAD_CONST               1 (0) 
                 18 LOAD_CONST               3 (()) 
                 21 COMPARE_OP               7 (not in) 
                 24 POP_JUMP_IF_FALSE       30 
                 27 JUMP_FORWARD             0 (to 30) 
    
      4     >>   30 LOAD_CONST               1 (0) 
                 33 LOAD_CONST               4 (()) 
                 36 COMPARE_OP               8 (is) 
                 39 POP_JUMP_IF_FALSE       45 
                 42 JUMP_FORWARD             0 (to 45) 
    
      5     >>   45 LOAD_CONST               1 (0) 
                 48 LOAD_CONST               5 (()) 
                 51 COMPARE_OP               9 (is not) 
                 54 POP_JUMP_IF_FALSE       60 
                 57 JUMP_FORWARD             0 (to 60) 
    
      6     >>   60 LOAD_CONST               0 (None) 
                 63 RETURN_VALUE         
    >>> 
    

    As you can see, there is a difference in each operator; and their codes (in order) are 6, 7, 8, and 9.

    0 讨论(0)
提交回复
热议问题