Applications of '~' (tilde) operator in Python Applications of '~' (tilde) operator in Python python python

Applications of '~' (tilde) operator in Python


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 << and >>. 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 + and - only for meaningful operations, you should try to do the same for bitwise operators.


The reason ~~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 int. So bool actually inherits the logic of all bitwise and arithmetical operators. That’s why True + True == 2 etc.


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?

Typically, you would not want to overload the ~ operator just because it is fun. It makes reading difficult. But sometimes, such overload for types other than int makes sense. Take a look at how SQLAlchemy puts it to good use.


It's commonly used in code golf as a shortcut for a few things, such as using ~x rather than -x-1 or ~my_bool rather than not my_bool.