gh-82012: Deprecate bitwise inversion (~) of bool (#103487)

The bitwise inversion operator on bool returns the bitwise inversion of the
underlying int value; i.e. `~True == -2` such that `bool(~True) == True`.

It's a common pitfall that users mistake `~` as negation operator and actually
want `not`. Supporting `~` is an artifact of bool inheriting from int. Since there
is no real use-case for the current behavior, let's deprecate `~` on bool and
later raise an error. This removes a potential source errors for users.

Full reasoning: https://github.com/python/cpython/issues/82012#issuecomment-1258705971

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
Co-authored-by: Shantanu <12621235+hauntsaninja@users.noreply.github.com>
This commit is contained in:
Tim Hoffmann 2023-05-03 09:00:42 +02:00 committed by GitHub
parent 5b05b013ff
commit fdb3ef8c0f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 78 additions and 25 deletions

View file

@ -73,6 +73,22 @@ bool_vectorcall(PyObject *type, PyObject * const*args,
/* Arithmetic operations redefined to return bool if both args are bool. */
static PyObject *
bool_invert(PyObject *v)
{
if (PyErr_WarnEx(PyExc_DeprecationWarning,
"Bitwise inversion '~' on bool is deprecated. This "
"returns the bitwise inversion of the underlying int "
"object and is usually not what you expect from negating "
"a bool. Use the 'not' operator for boolean negation or "
"~int(x) if you really want the bitwise inversion of the "
"underlying int.",
1) < 0) {
return NULL;
}
return PyLong_Type.tp_as_number->nb_invert(v);
}
static PyObject *
bool_and(PyObject *a, PyObject *b)
{
@ -119,7 +135,7 @@ static PyNumberMethods bool_as_number = {
0, /* nb_positive */
0, /* nb_absolute */
0, /* nb_bool */
0, /* nb_invert */
(unaryfunc)bool_invert, /* nb_invert */
0, /* nb_lshift */
0, /* nb_rshift */
bool_and, /* nb_and */