Skip to content

scipy/empty-csr-write

Rule empty-csr-write
Pack SciPy
Severity warning
Fix none, edit by hand
Library versions every version

Writing into a CSR or CSC matrix that started empty warns, raises under python -W error, and copies the whole matrix each time. Build it as lil_array, dok_array or from coordinates, then convert once.

A = sparse.csr_matrix((n, n))
A = sparse.lil_array((n, n))
for i, j, v in triples:
A[i, j] = v
A = A.tocsr()

The rule reports a write into a csr_matrix, csc_matrix, csr_array or csc_array built from a shape alone, as in A = csr_matrix((n, m)) followed by A[i, j] = v, A[i, j] += v or a slice write, in a function that doesn't assign A again. Each write adds a stored value and copies the whole matrix. On SciPy 1.18.1 a write emits SparseEfficiencyWarning, which raises under python -W error. Moreover, 1,000 writes ran 30 times slower than the same writes into a lil_matrix.

xpd has no automatic fix, so make the change by hand.

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

$A starts as an empty $N, and a later write into it adds a stored value, which emits SparseEfficiencyWarning, raises under python -W error, and copies the whole matrix each time. Build it as lil_array or dok_array, or collect the coordinates and pass them to coo_array, and call tocsr or tocsc once at the end.

Browse the other rules of the SciPy pack.