Search code examples
pythonscipysparse-matrix

what is wrong with importing modules in scipy , is it a bug?


ok , i don't think, i can explain this problem in words so , here is the snippet of ipython session , where i import scipy , in order to construct a sparse matrix.

In [1]: import scipy as sp

In [2]: a = sp.sparse.lil_matrix((5,5))
        ---------------------------------------------------------------------------
        AttributeError                            Traceback (most recent call last)
       /home/liveuser/<ipython-input-2-b5a55fc2d0ac> in <module>()
        ----> 1 a = sp.sparse.lil_matrix((5,5))

        AttributeError: 'module' object has no attribute 'sparse'

In [3]: import scipy.sparse as spar

In [4]: ax = spar.lil_matrix((5,5))

In [5]: a = sp.sparse.lil_matrix((5,5)) # you are kidding me?

In [6]: a
Out[6]: 
       <5x5 sparse matrix of type '<type 'numpy.float64'>'
       with 0 stored elements in LInked List format>

In [7]: ax
Out[7]: 
       <5x5 sparse matrix of type '<type 'numpy.float64'>'
       with 0 stored elements in LInked List format>

what is happening there , why can't construct a sparse matrix using sp , in the first time , when i import sparse sub-module in a particular way (as in snippet) , both sp and spar variables can now be used to construct sparse matrices.(i guess they are just references to same object)

I reproduced this python default shell , (so it is not ipython specific)

what's going on , is it by design?? if so kindly elaborate. or is it a bug??

My system is Fedora 16 KDE-scientific,64 bit.


Solution

  • This is an artifact of Python's importing, not of SciPy. Do

    from scipy import sparse [as sp]
    

    or

    import scipy.sparse [as sp]
    

    (where [] is meta-notation for optionality).

    In short, the import statement needs to know the module's "true" name, not some abbreviation created by an import as statement.