Grayscale
Grayscale

Reputation: 1532

How does Python import work in this example?

I get an error if I do the following:

import scipy as sp
sp.sparse.identity(10)

The error is:

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

From this, I infer that I need to explicitly import scipy.sparse. However, if I instead "go too far" and import scipy.sparse.linalg, I get no error:

import scipy.sparse.linalg as sla
import scipy as sp
sp.sparse.identity(10)

This is rather unintuitive to me. What happened? Why does it work like this?

Upvotes: 0

Views: 160

Answers (2)

Souldiv
Souldiv

Reputation: 165

I believe the reason is because of a broken install as stated in the closed issue of github. I think python is confusing between two different modules named the same.

Here is the link to the issue:

https://github.com/scikit-learn/scikit-learn/issues/13678

Upvotes: 0

Sahith Kurapati
Sahith Kurapati

Reputation: 1715

The problem is, since scipy is very large, it doesn't import all the modules directly. You can only only import the ones you require directly. There are a lot more packages which do this. They are generally very large.

As it's a separate sub-package, once you import it, it's attributes are available to you by using the regular scipy.module.attribute

Hope you understood :)

Upvotes: 1

Related Questions