Type hinting for scipy sparse matrices

Question:

How do you type hint scipy sparse matrices, such as CSR, CSC, LIL etc.? Below is what I have been doing, but it doesn’t feel right:

def foo(mat: scipy.sparse.csr.csr_matrix):
    # Do whatever

What do we do if our function can accept multiple types of scipy sparse matrices (i.e any of them)?

Asked By: yippingAppa

||

Answers:

All of csr, csc, lil are types of scipy.sparse.base.spmatrix:

from scipy import sparse
c1 = sparse.lil.lil_matrix
c2 = sparse.csr.csr_matrix
c3 = sparse.csc.csc_matrix

print(c1.__bases__[0])
print(c2.__base__.__base__.__base__)
print(c3.__base__.__base__.__base__)

Output:

<class 'scipy.sparse.base.spmatrix'>
<class 'scipy.sparse.base.spmatrix'>
<class 'scipy.sparse.base.spmatrix'>

So you have an option to:

def foo(mat: scipy.sparse.base.spmatrix):
    # Do whatever
Answered By: aminrd

spicy.sparse.base is now deprecated. You should use spicy.sparse.spmatrix instead, which provides a base class for all sparse matrices.

def foo(mat: spicy.sparse.spmatrix):
    # Whatever you want
    pass
Answered By: Jérémie Dentan
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.