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 __invert__
method) for other uses. The example given in the question fails with a TypeError
, and the link provided seems pretty intimidating. Here's some fiddling around to see ~
in use:
from bitstring import BitArray
x = 7
print(~x)
# -8
print(BitArray(int=x, length=4).bin)
# '0111'
print(BitArray(int=~x, length=4).bin)
# '1000'
print(~~True, ~~False)
# 1 0
for i in range(-100, 100):
assert i + ~i == -1
assert i ^ ~i == -1
assert bool(i) == ~~bool(i)
Are there any examples of valid use-cases for this operator that I should be aware of? And even if there are, is it generally acceptable to override this operator for types other than int
?
arr = [True, False, True]
,~arr
returns[False, True, False]
. – Cherilyncherilynnint
s andbool
s:~np.array([1, 0, -1, True, False]) -> array([-2, -1, 0, -2, -1])
. Could be used as a funky trick to convertbool
values intoint
values though:~~(np.array([True, False] + [1]))[:-1] -> array([1, 0])
– Katowicebool
s or an array ofint
s. Mixingbool
s andint
s yields anint
array. – Tachymetry