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.DataFrameoften used withDataFrame.mask,DataFrame.wherepandas.Seriesoften used withSeries.mask,Series.wherenumpy.Arrayoften used withArray.wheresqlalchemy.Columnoften 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)
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
- Update docs for `literal-comparisons` (#4560) - Add fix safety blurbs for E711 `NoneComparison` & E712 `TrueFalseComparison` - same for both rules. - Minor formatting for E711 `NoneComparison`. — committed to psychedelicious/ruff by psychedelicious 2 years ago
- Update docs for E711, E712 (#4560) The fixes for rules E711 `NoneComparison` and E712 `TrueFalseComparison` are marked unsafe due to possible runtime behavior changes with libraries that override `__... — committed to psychedelicious/ruff by psychedelicious 2 years ago
- Update docs for `literal-comparisons` (#4560) - Link to the relevant GH issue instead of copying examples/alternatives from the GH issue. — committed to psychedelicious/ruff by psychedelicious 2 years ago
- Update docs for E711, E712 (#4560) The fixes for rules E711 `NoneComparison` and E712 `TrueFalseComparison` are marked unsafe due to possible runtime behavior changes with libraries that override `__... — committed to psychedelicious/ruff by psychedelicious 2 years ago
- Update docs for E711, E712 (#4560) (#11859) — committed to astral-sh/ruff by psychedelicious 2 years ago
- Add known problems warning to `type-comparison` rule (#12769) ## Summary See: https://github.com/astral-sh/ruff/issues/4560 — committed to astral-sh/ruff by charliermarsh 2 years ago
- chore: Move the 'ignore' `ruff` has a rough time inferring that this is an element-wise comparison of an array See https://github.com/astral-sh/ruff/issues/4560 for more details — committed to equinor/APS-Facies by sindre-nistad a year ago
- chore: Move the 'ignore' `ruff` has a rough time inferring that this is an element-wise comparison of an array See https://github.com/astral-sh/ruff/issues/4560 for more details — committed to equinor/APS-Facies by sindre-nistad a year ago
I just spent a while tracking down this exact issue, an error introduced by ruff and reduced to the almost identical:
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
iswith boolean constants:So while the autofix may be unsafe, I would argue the diagnostics itself is harmful. The correct suggestion would be to drop
== Trueentirely (though PySpark is certainly another special case, as== Falsewould need a conversion to the unary not~operator …)Note about SQLAlchemy:
The
.is_and.is_notmethods may not be safe alternatives to the equality (==/!=) operators, becauseISand=are different SQL operators. Consider the following example in MySQL:Thus, the safe alternative for comparing to booleans is:
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, andif _should be used or whetherE712is 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
pysparkcode by converting code similar to:to
which leads to
TypeError: condition should be string or ColumnThank you