Why does this AttributeError in python occur?

Aufwind picture Aufwind · Jan 2, 2012 · Viewed 103.5k times · Source

There is one thing, that I do not understand.

Why does this

import scipy # happens with several other modules, too. I took scipy as an example now...

matrix = scipy.sparse.coo_matrix(some_params)

produce this error:

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

Answer

David Z picture David Z · Jan 2, 2012

This happens because the scipy module doesn't have any attribute named sparse. That attribute only gets defined when you import scipy.sparse.

Submodules don't automatically get imported when you just import scipy; you need to import them explicitly. The same holds for most packages, although a package can choose to import its own submodules if it wants to. (For example, if scipy/__init__.py included a statement import scipy.sparse, then the sparse submodule would be imported whenever you import scipy.)