I just discovered the bitwise complement unary operation in Python via this question and have been trying to come up with an actual application for it, and if not, to determine if it's generally safe to overload the operator (by overriding the
from bitstring import BitArray
x = 7
# 1 0
for i in range(-100, 100):
assert i + ~i == -1
assert i ^ ~i == -1
assert bool(i) == ~~bool(i)
The standard use cases for the bitwise NOT operator are bitwise operations, just like the bitwise AND
&, the bitwise OR
|, the bitwise XOR
^, and bitwise shifting
>>. Although they are rarely used in higher level applications, there are still some times where you need to do bitwise manipulations, so that’s why they are there.
Of course, you may overwrite these for custom types, and in general you are not required to follow any specific semantics when doing so. Just choose what makes sense for your type and what still fits the operator in some way.
If the operation is obscure and better explained with a word or two, then you should use a standard method instead. But there are some situations, especially when working with number related types, that could have some mathematical-like operations which fit the bitwise operators, and as such are fine to use those.
Just like you would overwrite standard operators like
- only for meaningful operations, you should try to do the same for bitwise operators.
~~True, ~~False gives you
(1, 0) is because the
bool type does not define its own
__invert__ operation. However,
int does; and
bool is actually a subtype of
bool actually inherits the logic of all bitwise and arithmetical operators. That’s why
True + True == 2 etc.