Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 284
user3317287 Avatar asked Jan 02 '15 15:01

user3317287


People also ask

What are the different methods of importing the Python module?

So there's four different ways to import: Import the whole module using its original name: pycon import random. Import specific things from the module: pycon from random import choice, randint. Import the whole module and rename it, usually using a shorter variable name: pycon import pandas as pd.

What is the difference between import NumPy as NP from NumPy import *?

using from numpy import array , you only import the array module. you cannot use other functions of numpy. with import numpy as np , you import all the numpy modules and you can use them as np.

What happens when you import a module Python?

When a module is first imported, Python searches for the module and if found, it creates a module object 1, initializing it. If the named module cannot be found, a ModuleNotFoundError is raised. Python implements various strategies to search for the named module when the import machinery is invoked.

What does import NumPy in Python?

The import numpy portion of the code tells Python to bring the NumPy library into your current environment. The as np portion of the code then tells Python to give NumPy the alias of np. This allows you to use NumPy functions by simply typing np.


1 Answers

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.

like image 116
gg349 Avatar answered Oct 09 '22 22:10

gg349