Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shifting and binary bitwise operators applies on boolean arguments

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 ?

  • True & False: False (class 'bool')
  • True | False: True (class 'bool')
  • True ^ False: True (class 'bool')
  • ~ True: -2 (class 'int')
  • ~ False: -1 (class 'int')
  • True << True: 2 (class 'int')
  • False >> False: 0 (class 'int')

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')
like image 293
Morten Zilmer Avatar asked May 03 '26 13:05

Morten Zilmer


1 Answers

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.

like image 171
Bakuriu Avatar answered May 05 '26 15:05

Bakuriu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!