Boolean confusion
Peter Hansen
peter at engcorp.com
Fri Oct 31 13:58:15 EST 2003
Frantisek Fuka wrote:
>
> Can anyone please explain why these two give different results in Python
> 2.3?
>
> >>> 'a' in 'abc' == 1
> False
> >>> ('a' in 'abc') == 1
> True
>
> I know it's not a good idea to compare boolean with Integer but that's
> not the answer to my question.
Hmm....
>>> dis.dis(lambda : 'a' in 'abc' == 1)
1 0 LOAD_CONST 1 ('a')
3 LOAD_CONST 2 ('abc')
6 DUP_TOP
7 ROT_THREE
8 COMPARE_OP 6 (in)
11 JUMP_IF_FALSE 10 (to 24)
14 POP_TOP
15 LOAD_CONST 3 (1)
18 COMPARE_OP 2 (==)
21 JUMP_FORWARD 2 (to 26)
>> 24 ROT_TWO
25 POP_TOP
>> 26 RETURN_VALUE
>>> dis.dis(lambda : ('a' in 'abc') == 1)
1 0 LOAD_CONST 1 ('a')
3 LOAD_CONST 2 ('abc')
6 COMPARE_OP 6 (in)
9 LOAD_CONST 3 (1)
12 COMPARE_OP 2 (==)
15 RETURN_VALUE
Judging by the "odd" (unexpected) code in the first example,
"A in B == C" is actually doing operator chaining, in a manner
similar to "A < B < C". Since 'a' is in 'abc' but 'abc' is
not equal to 1, the chained test fails.
I can't comment further on the validity of such a thing, but
there you have it.
-Peter
More information about the Python-list
mailing list