numpy/per-value-comprehension
| Pack | Severity | Fix | Versions |
|---|---|---|---|
| NumPy | warning | unsafe, with xpd check --fix --unsafe-fixes |
All versions |
A comprehension that applies arithmetic or a math function to each value runs Python once for every value, which was 60 to 470 times slower. Apply the expression to the whole array.
roots = np.array([math.sqrt(x) for x in values])roots = np.sqrt(np.asarray(values))What the rule reports
Section titled “What the rule reports”The rule reports np.array([x * 2 + 1 for x in a]), np.array([math.sqrt(x) for x in a]), np.array([i * 0.5 for i in range(n)]) and map(np.sqrt, a), where the element is arithmetic or a NumPy or math function on the loop variable.
A comprehension with a filter, a second for, or a power with the loop variable in the exponent is left alone. The map form leaves a literal list or tuple of arrays 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 the element with the loop variable replaced by np.asarray(a), as in np.asarray(a) * 2 + 1, or by np.arange(n) for a range, and np.sqrt(np.asarray(a)) for map. Python ints do not wrap where int64 does, a division by zero gives inf where Python raised, and map returned an iterator. An element with if, and, or, not, min, max or a math function, and a loop over a call, have no fix.
An empty range can produce a different dtype. Converting a list of lists to an array also changes how the operation handles rows. For the map form, the replacement returns an array that can be read repeatedly, and some values that made a Python math function raise can yield NaN.
Diagnostic message
Section titled “Diagnostic message”This runs Python once per value of $IT. Apply the expression to the whole array instead, with $X replaced by np.asarray($IT), which ran 60 to 470 times faster on 1,000,000 values of an array and 2 to 24 times faster on a list.See all rules in the NumPy pack.