Skip to content

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)]

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.

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.

The & and | operators bind tighter than comparisons, so this compares against a combined value. Write $FIXED.

See all rules in the NumPy pack.