Open
Description
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 withDataFrame.mask
,DataFrame.where
pandas.Series
often used withSeries.mask
,Series.where
numpy.Array
often used withArray.where
sqlalchemy.Column
often used withQuery.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)