Skip to content

numpy/needless-copy

Rule needless-copy
Pack NumPy
Severity warning
Fix unsafe, with xpd check --fix --unsafe-fixes
Library versions every version

flatten() and copy() on an array that is already a new copy copy it again. Use ravel() or drop the extra copy.

flat = np.concatenate([a, b]).flatten()
flat = np.concatenate([a, b]).ravel()

The rule reports .flatten() on the result of a NumPy call that returns a new array, x.copy().astype(t) and np.array(x).copy(). Each one copies an array that is already a new copy.

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 np.abs(m).ravel(), x.astype(np.float32), np.array(x). ravel can return a view of an output array that was passed by position, and the other two can change the memory order.

xpd prints this message with the issue. A name that starts with $ stands for code from your file.

$NP.$F already returns a new array, so flatten copies it again. Write .ravel(), which ran 1.6 to 1.8 times faster on 1,000,000 values.

Browse the other rules of the NumPy pack.