11from __future__ import annotations
22from struct import pack , unpack_from
3- from typing import Any , overload
3+ from typing import TYPE_CHECKING , Any , overload
4+ from ._utils import is_sparse_array
45
5- try :
6+ if TYPE_CHECKING :
67 import numpy as np
7- except ImportError :
8- pass
9-
10- try :
118 from scipy .sparse import sparray , spmatrix , coo_array , coo_matrix
12- SCIPY_AVAILABLE = True
13- except ImportError :
14- SCIPY_AVAILABLE = False
9+
1510
1611NO_DEFAULT = object ()
1712
@@ -26,7 +21,7 @@ def __init__(self, value: list[float] | np.ndarray[tuple[int, ...], np.dtype[np.
2621 ...
2722
2823 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 :
29- if SCIPY_AVAILABLE and isinstance (value , ( sparray , spmatrix ) ):
24+ if is_sparse_array (value ):
3025 if dimensions is not NO_DEFAULT :
3126 raise ValueError ('extra argument' )
3227
@@ -61,6 +56,8 @@ def values(self) -> list[float]:
6156 return self ._values
6257
6358 def to_coo (self ) -> coo_array :
59+ from scipy .sparse import coo_array
60+
6461 coords = ([0 ] * len (self ._indices ), self ._indices )
6562 return coo_array ((self ._values , coords ), shape = (1 , self ._dim ))
6663
@@ -71,6 +68,8 @@ def to_list(self) -> list[float]:
7168 return vec
7269
7370 def to_numpy (self ) -> np .ndarray [tuple [int , ...], np .dtype [np .float32 ]]:
71+ import numpy as np
72+
7473 vec = np .repeat (0.0 , self ._dim ).astype (np .float32 )
7574 for i , v in zip (self ._indices , self ._values ):
7675 vec [i ] = v
0 commit comments