I was testing some piece of code
True = 2
print 1 - (1 == 1)
print True == (1 == 1)
Then I was expecting:
-1
True
But I got this instead:
0
False
So, I did what any python programmer would do: disassemble it.
def f():
True = 2
print 1 - (1 == 1)
print True == (1 == 1)
2 0 LOAD_CONST 1 (2)
3 STORE_FAST 0 (True)
3 6 LOAD_CONST 2 (1)
9 LOAD_CONST 2 (1)
12 LOAD_CONST 2 (1)
15 COMPARE_OP 2 (==)
18 BINARY_SUBTRACT
19 PRINT_ITEM
20 PRINT_NEWLINE
4 21 LOAD_FAST 0 (True)
24 LOAD_CONST 2 (1)
27 LOAD_CONST 2 (1)
30 COMPARE_OP 2 (==)
33 COMPARE_OP 2 (==)
36 PRINT_ITEM
37 PRINT_NEWLINE
38 LOAD_CONST 0 (None)
41 RETURN_VALUE
Then it was a bit clear, is using the COMPARE_OP (==). Witch should return a boolean but it appears that it returns a integer instead. Any ideas why?
Edit:
In short the lesson learned: Changing the values of True or False doesn't change how the boolean logic is represented behind the scene.
In Python, bool is a subclass of int, and False and True have the equivalent values of 0 and 1 respectively. Also, __eq__() can return any object it likes; it just so happens that for built-in types it returns bool instances.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With