# 10.5. Operator Boolean¶

• & - and

• | - or

• ^ - xor

• &= - iand

• |= - ior

• ^= - ixor

• << - lshift

• >> - rshift

• <<= - ilshift

• >>= - irshift

Operator

Method

obj & other

obj.__and__(other)

obj | other

obj.__or__(other)

obj ^ other

obj.__xor__(other)

obj &= other

obj.__iand__(other)

obj |= other

obj.__ior__(other)

obj ^= other

obj.__ixor__(other)

obj << other

obj.__lshift__(other)

obj >> other

obj.__rshift__(other)

obj <<= other

obj.__ilshift__(other)

obj >>= other

obj.__irshift__(other)

## 10.5.2. Operator Module - AND¶

1 & 1 = 1
1 & 0 = 0
0 & 1 = 0
0 & 0 = 0

>>> from operator import and_
>>>
>>>
>>> and_(True, True)
True
>>> and_(True, False)
False
>>> and_(False, True)
False
>>> and_(False, False)
False


## 10.5.3. Operator Module - OR¶

1 | 1 = 1
1 | 0 = 1
0 | 1 = 1
0 | 0 = 0

>>> from operator import or_
>>>
>>>
>>> or_(True, True)
True
>>> or_(True, False)
True
>>> or_(False, True)
True
>>> or_(False, False)
False


## 10.5.4. Operator Module - XOR¶

1 ^ 1 = 0
1 ^ 0 = 1
0 ^ 1 = 1
0 ^ 0 = 0

>>> from operator import xor
>>>
>>>
>>> xor(True, True)
False
>>> xor(True, False)
True
>>> xor(False, True)
True
>>> xor(False, False)
False


## 10.5.5. Use Case - 0x01¶

• XOR as pow

• Excel uses ^ to rise number to the power of a second number

>>> from dataclasses import dataclass
>>>
>>>
>>> @dataclass
... class Number:
...     value: int
...
...     def __xor__(self, other):
...         return Number(self.value ** other.value)
>>>
>>>
>>> a = Number(2)
>>> b = Number(4)
>>>
>>> a ^ b
Number(value=16)


## 10.5.6. Use Case - 0x02¶

• Numpy

>>> import numpy as np
>>>
>>>
>>> a = np.array([[1, 2, 3],
...                  [4, 5, 6],
...                  [7, 8, 9]])
>>>
>>> a > 2
array([[False, False,  True],
[ True,  True,  True],
[ True,  True,  True]])
>>>
>>> (a>2) & (a<7)
array([[False, False,  True],
[ True,  True,  True],
[False, False, False]])
>>>
>>> (a>2) & (a<7) | (a>3)
array([[False, False,  True],
[ True,  True,  True],
[ True,  True,  True]])


Python understands this:

>>> ~( (a>2) & (a<7) | (a>3) )
array([[ True,  True, False],
[False, False, False],
[False, False, False]])


As as chained calls of the following methods:

>>> a.__gt__(2).__and__(a.__lt__(7)).__or__(a.__gt__(3)).__invert__()
array([[ True,  True, False],
[False, False, False],
[False, False, False]])


## 10.5.7. Use Case - 0x03¶

• Game

>>> hero >> Direction(left=10, up=20)