Applications of '~' (tilde) operator in Python
<p>I just discovered the <a href="https://en.wikipedia.org/wiki/Bitwise_operation#NOT">bitwise complement unary operation</a> in Python via <a href="https://stackoverflow.com/questions/8305199/the-tilde-operator-in-python">this question</a> 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 <code>__invert__</code> method) for other uses. The example given in the question fails with a <code>TypeError</code>, and the <a href="https://graphics.stanford.edu/~seander/bithacks.html">link</a> provided seems pretty intimidating. Here's some fiddling around to see <code>~</code> in use:</p>

<pre><code>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)
</code></pre>

<p>Are there <em>any</em> 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 <code>int</code>?</p>