numpy/mask-operator-precedence
| Pack | Severity | Fix | Versions |
|---|---|---|---|
| NumPy | error | unsafe, with xpd check --fix --unsafe-fixes |
All versions |
Python applies & and | before comparisons, so x > 2 & x < 8 compares against the wrong value. Put each comparison in parentheses.
inside = x[x > 2 & x < 8]inside = x[(x > 2) & (x < 8)]What the rule reports
Section titled “What the rule reports”The rule reports x > 2 & x < 8. Python applies & before the comparisons, so the code compares x with 2 & x.
The rule requires a chained comparison. A single comparison such as x == A | B can be ordinary flag arithmetic and is left alone.
How to fix it
Section titled “How to fix it”xpd check --fix --unsafe-fixes applies the fixes of this rule. Check the result, because an unsafe fix can change what the code does.
The unsafe fix writes (x > 2) & (x < 8) when the four operands are names, numbers or attributes. Other operands have no fix.
In a file that imports pandas, the pandas rule mask-precedence reports the code instead.
Diagnostic message
Section titled “Diagnostic message”The & and | operators bind tighter than comparisons, so this compares against a combined value. Write $FIXED.See all rules in the NumPy pack.