Python documentation for shifting operations and binary bitwise operations says that arguments must be integers, but the below expressions evaluates without error, however giving odd results for << and >>.
Is there an additional place I should look for documentation of & etc. when using boolean arguments, or is there some good explanation for evaluation and results ?
Code:
# Python ver. 3.3.2
def tryout(s):
print(s + ':', eval(s), type(eval(s)))
tryout('True & False')
tryout('True | False')
tryout('True ^ False')
tryout('~ True')
tryout('~ False')
tryout('True << True')
tryout('False >> False')
bool is a subclass of int, hence they are integers. In particolar True behaves like 1 and False behaves like 0.
Note that bool only reimplements &, | and ^(source: source code at Objects/boolobject.c in the python sources), for all the other operations the methods of int are used[actually: inherited], hence the results are ints and the semantics are those of the integers.
Regarding << and >>, the expression True << True is equivalent to 1 << 1 i.e. 1 * 2 == 2, while False >> False is 0 >> 0, i.e. 0 * 1 == 0.
You should think python's True and False as 1 and 0 when doing arithmetic operations on them. The reimplementation of &, | and ^ only affect the return type, not the semantics.
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