[python] Why does this AttributeError in python occur?

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'

This question is related to python import attributeerror

The answer is


AttributeError is raised when attribute of the object is not available.

An attribute reference is a primary followed by a period and a name:

attributeref ::= primary "." identifier

To return a list of valid attributes for that object, use dir(), e.g.:

dir(scipy)

So probably you need to do simply: import scipy.sparse


The default namespace in Python is "__main__". When you use import scipy, Python creates a separate namespace as your module name. The rule in Pyhton is: when you want to call an attribute from another namespaces you have to use the fully qualified attribute name.


Because you imported scipy, not sparse. Try from scipy import sparse?


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to import

Import functions from another js file. Javascript The difference between "require(x)" and "import x" pytest cannot import module while python can How to import an Excel file into SQL Server? When should I use curly braces for ES6 import? How to import a JSON file in ECMAScript 6? Python: Importing urllib.quote importing external ".txt" file in python beyond top level package error in relative import Reading tab-delimited file with Pandas - works on Windows, but not on Mac

Examples related to attributeerror

Why Python 3.6.1 throws AttributeError: module 'enum' has no attribute 'IntFlag'? Beginner Python: AttributeError: 'list' object has no attribute AttributeError: 'str' object has no attribute AttributeError: 'DataFrame' object has no attribute AttributeError: 'module' object has no attribute 'urlretrieve' "import datetime" v.s. "from datetime import datetime" Python: instance has no attribute AttributeError("'str' object has no attribute 'read'") Why do I get AttributeError: 'NoneType' object has no attribute 'something'? Why does this AttributeError in python occur?