Differences in importing modules/subpackages of nu

2019-01-27 21:56发布

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?

1条回答
戒情不戒烟
2楼-- · 2019-01-27 22:15

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.

查看更多
登录 后发表回答