ruff: Fix (E712) changing `==`/`!=` to `is`/`is not` is not correct for some types

Summary

Generally, comparisons to True, False, and None singletons should use obj is True instead of obj == True.

However, it is common for libraries to override the ==/__eq__ operator to create simple APIs for filtering data. In these cases, correcting == to is changes the meaning of the program and breaks the user’s code. The same applies for != and is not.

This is a tracking issue for all invalid corrections from this rule.

Types with the issue

  • pandas.DataFrame often used with DataFrame.mask, DataFrame.where
  • pandas.Series often used with Series.mask, Series.where
  • numpy.Array often used with Array.where
  • sqlalchemy.Column often used with Query.having, Query.filter, Query.where

If an issue with an unlisted type is encountered please reply and I will edit to add it here.

Resolution

Eventually, ruff is likely to detect these cases by inferring the datatype involved and exclude it from the suggested fix.

In the meantime, you may:

  • Disable rule E712
  • Use an alternative comparison method that is not ambiguous (e.g. pandas.Series.eq)

Examples

import numpy

numpy.array([True, False]) == False
# array([False,  True])

numpy.array([True, False]) is False
# False
import pandas

pandas.Series([True, False]) == False
# 0    False
# 1    True
# dtype: bool

pandas.Series([True, False]) is False
# False

# Alternative safe syntax
pandas.Series([True, False]).eq(False)
pandas.DataFrame({"x": [True, False]}) == False
#       x
# 0  False
# 1  True

pandas.DataFrame({"x": [True, False]}) is False
# False

# Alternative safe syntax
pandas.DataFrame({"x": [True, False]}).eq(False)
import sqlalchemy
c = sqlalchemy.Column("foo", sqlalchemy.Boolean)

c == True
# <sqlalchemy.sql.elements.BinaryExpression object at 0x12ed532e0>

c is True
# False

# Alternative safe syntax
c.is_(True)
c.is_not(False)

Related issues

About this issue

  • Original URL
  • State: open
  • Created 4 years ago
  • Reactions: 27
  • Comments: 21 (7 by maintainers)

Commits related to this issue

Most upvoted comments

I just spent a while tracking down this exact issue, an error introduced by ruff and reduced to the almost identical:

import numpy as np

arr = np.array([False, True, False, True])
print(repr(arr == False))
# array([ True, False,  True, False])
print(repr(arr is False))
# False

Reading the other thread, it sounds like this autofix can’t be made safe. I would suggest disabling it completely then, because using truthiness in numpy comparison isn’t a rare operation, and expecting everyone to “know” not to do this seems to defeat the point of an autocorrecting linter.

Note as of v0.1.0 we do not apply unsafe fixes by default — so this fix will not be applied by default.

Adding to @nicornk: PEP-8 actually strongly discourages using is with boolean constants:

Don’t compare boolean values to True or False using ==:
# Correct:
if greeting:
# Wrong:
if greeting == True:
Worse:

# Wrong:
if greeting is True:

So while the autofix may be unsafe, I would argue the diagnostics itself is harmful. The correct suggestion would be to drop == True entirely (though PySpark is certainly another special case, as == False would need a conversion to the unary not ~ operator …)

Note about SQLAlchemy:

The .is_ and .is_not methods may not be safe alternatives to the equality (==/!=) operators, because IS and = are different SQL operators. Consider the following example in MySQL:

SELECT 10 IS TRUE;
/* 1 */
SELECT 10 = TRUE;
/* 0 */
SELECT NULL IS NOT FALSE;
/* 1 */
SELECT NULL != FALSE;
/* NULL */

Thus, the safe alternative for comparing to booleans is:

c == True
# <sqlalchemy.sql.elements.BinaryExpression object at 0x1026203e0>
c == sqlalchemy.true()
# <sqlalchemy.sql.elements.BinaryExpression object at 0x1026222a0>

Thanks @psychedelicious. Would you be willing to open a pull request?

Same thing with E711.

Would be nice to have a brief mention in the rule’s docs calling out common situations where this is unsafe and why

Please let’s not make this issue a debate about how if _ == True, if _ is True, and if _ should be used or whether E712 is valid in general.

The libraries that are the focus of this issue have designed APIs where specific comparisons are necessary. This issue is intended to track support for patterns in those APIs. I’d recommend creating a new discussion if you want to discuss broader concerns.

Any conclusion on this one? This issue broke a bunch of our pyspark code by converting code similar to:

df = df.where(F.col("colName") == True)

to

df = df.where(F.col("colName") is True)

which leads to TypeError: condition should be string or Column

Thank you