Python's strange behavior is an operator if combined with 'in'

How does Python interpret "a" in "abc" True? "I tried to evaluate the following two expressions:

>>> 'a' in 'abc' is True: False >>> ('a' in 'abc') is True: True 

(I know that the "keyword" is usually not used to compare with True , this is just an example)

+6
source share
1 answer

Interest Ask!

Here is the bytecode from 'a' in 'abc' is True :

 >>> import dis >>> dis.disassemble((lambda: 'a' in 'abc' is True).func_code) 2 0 LOAD_CONST 1 ('a') # stack: 'a' 3 LOAD_CONST 2 ('abc') # stack: 'a' 'abc' 6 DUP_TOP # stack: 'a' 'abc' 'abc' 7 ROT_THREE # stack: 'abc' 'a' 'abc' 8 COMPARE_OP 6 (in) # stack: 'abc' True 11 JUMP_IF_FALSE_OR_POP 21 # stack: 'abc' 14 LOAD_GLOBAL 0 (True) # stack: 'abc' True 17 COMPARE_OP 8 (is) # stack: False 20 RETURN_VALUE >> 21 ROT_TWO 22 POP_TOP 23 RETURN_VALUE 

And compare with that of ('a' in 'abc') is True :

 >>> import dis >>> dis.disassemble((lambda: ('a' in 'abc') is True).func_code) 1 0 LOAD_CONST 1 ('a') # stack: 'a' 3 LOAD_CONST 2 ('abc') # stack: 'a' 'abc' 6 COMPARE_OP 6 (in) # stack: True 9 LOAD_GLOBAL 0 (True) 12 COMPARE_OP 8 (is) 15 RETURN_VALUE 

So, the expression 'a' in 'abc' is True looks something like this:

 >>> 'a' in 'abc' and 'abc' is True 

This seems to be the result of a chain of statements: fooobar.com/questions/165474 / ... - the same magic that makes work 1 < 5 < 10 workable.

Very interesting!

(Note: this was done with CPython 2.7.2)

+10
source

Source: https://habr.com/ru/post/958105/


All Articles