numpy/result-discarded
| Pack | Severity | Fix | Versions |
|---|---|---|---|
| NumPy | error | unsafe, with xpd check --fix --unsafe-fixes |
All versions |
Functions such as np.sort and np.append return a new array and leave the input alone, so a call on its own line does nothing. Assign the result.
np.append(lengths, 1)lengths = np.append(lengths, 1)What the rule reports
Section titled “What the rule reports”The rule reports np.sort(x), np.append(x, 4), np.clip(x, 0, 1), x.astype(float) and m.reshape(3, 2) standing alone as a statement. Each call returns a new array that the code drops, so the statement does nothing.
The rule leaves alone a call with out=, a call in a try block or in a with pytest.raises block, and a call in a benchmark method of asv (airspeed velocity). In a file with a cell marker (# %%, # <codecell> or # In[1]:), the rule leaves the last statement of each cell alone, because an interactive window shows its value. After the fix, other names bound to the old array keep its old values.
The rule recognizes positional output arguments for functions such as np.sqrt(x, out) and methods such as x.clip(lo, hi, out). It also leaves calls inside warning checks alone. The method check can apply to pandas or PyTorch objects with the same method names.
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 = np.sort(x).
Diagnostic message
Section titled “Diagnostic message”$NP.$F returns a new array and leaves $X as it was, so this line does nothing. Write $X = $NP.$F($X, ...).See all rules in the NumPy pack.