77except ImportError :
88 pass
99
10+ try :
11+ from scipy .sparse import sparray , spmatrix
12+ SCIPY_AVAILABLE = True
13+ except ImportError :
14+ SCIPY_AVAILABLE = False
15+
1016NO_DEFAULT = object ()
1117
1218
@@ -16,15 +22,15 @@ def __init__(self, value: dict[int, float], dimensions: int, /) -> None:
1622 ...
1723
1824 @overload
19- def __init__ (self , value : list [float ], / ) -> None :
25+ def __init__ (self , value : list [float ] | np . ndarray [ tuple [ int ], np . dtype [ np . floating ]] , / ) -> None :
2026 ...
2127
2228 @overload
23- def __init__ (self , value : Any , / ) -> None :
29+ def __init__ (self , value : sparray | spmatrix , / ) -> None :
2430 ...
2531
26- def __init__ (self , value : dict [int , float ] | list [float ] | Any , dimensions : int | Any = NO_DEFAULT , / ) -> None :
27- if value . __class__ . __module__ . startswith ( 'scipy.sparse.' ):
32+ def __init__ (self , value : dict [int , float ] | list [float ] | np . ndarray [ tuple [ int ], np . dtype [ np . floating ]] | sparray | spmatrix , dimensions : int | Any = NO_DEFAULT , / ) -> None :
33+ if SCIPY_AVAILABLE and isinstance ( value , ( sparray , spmatrix ) ):
2834 if dimensions is not NO_DEFAULT :
2935 raise ValueError ('extra argument' )
3036
@@ -33,12 +39,12 @@ def __init__(self, value: dict[int, float] | list[float] | Any, dimensions: int
3339 if dimensions is NO_DEFAULT :
3440 raise ValueError ('missing dimensions' )
3541
36- self ._from_dict (value , dimensions )
42+ self ._from_dict (value , dimensions ) # type: ignore
3743 else :
3844 if dimensions is not NO_DEFAULT :
3945 raise ValueError ('extra argument' )
4046
41- self ._from_dense (value )
47+ self ._from_dense (value ) # type: ignore
4248
4349 def __repr__ (self ) -> str :
4450 elements = dict (zip (self ._indices , self ._values ))
@@ -108,7 +114,7 @@ def _from_sparse(self, value: Any) -> None:
108114 self ._indices = value .col .tolist ()
109115 self ._values = value .data .tolist ()
110116
111- def _from_dense (self , value : list [float ]) -> None :
117+ def _from_dense (self , value : list [float ] | np . ndarray [ tuple [ int ], np . dtype [ np . floating ]] ) -> None :
112118 self ._dim = len (value )
113119 self ._indices = [i for i , v in enumerate (value ) if v != 0 ]
114120 self ._values = [float (value [i ]) for i in self ._indices ]
@@ -149,7 +155,7 @@ def _from_parts(cls, dim: int, indices: list[int], values: list[float]) -> Spars
149155 return vec
150156
151157 @classmethod
152- def _to_db (cls , value : list [float ] | Any | SparseVector | None ) -> str | None :
158+ def _to_db (cls , value : list [float ] | np . ndarray [ tuple [ int ], np . dtype [ np . floating ]] | sparray | spmatrix | SparseVector | None ) -> str | None :
153159 if value is None :
154160 return value
155161
0 commit comments