Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
777 views
in Technique[技术] by (71.8m points)

python - Differences in importing modules/subpackages of numpy and Scipy packages

I am using scipy and numpy through Anaconda 2.1.0 distribution. I use Spyder as my Python IDE.

When I run import scipy as sp, I can't access the subpackages, such as optimize, linalg, cluster etc. through sp.

However, when I run import numpy as np, I am able to access all its subpackages, such as linalg, random, matrixlib, polynomial, testing, etc. through np.

Is there a reason why the two imports work in different ways? Why does import scipy as sp not grab all scipy subpackages into sp's namespace?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This possibility of different import behaviour occurs by design of the python language.

An import statement of a module(*) by default only imports the main module, and not the submodules. The main module may (like in the case of numpy) , or may not (like scipy) import some or all the submodules.

The reason behind this is exemplified by scipy: in most cases, you will need only one submodule of the scipy package. This default behaviour will not hang the interpreter at loading submodules that are unnecessary to your code.

EDIT: Notice that numpy does not import by default all the submodules, for example it does not load numpy.f2py, see THIS question/answer for more details.

(*) here I mean an import statement like import scipy or import scipy as sp, where a module is loaded. Of course if you write import scipy.optimize then python will first load the main module, and then the submodule.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...