Short answer
This is due to the fact that numpy.matlib is an additional numpy subpacker that must be imported separately.
The reason for this function may be:
- In particular, for
numpy numpy.matlib submodule overrides numpy functions to return matrices instead of ndarrays, an optional function that many might not need - In the general case, to load the parent module without loading the module with slow loading, which many users may not need often
- Maybe split namespace
When you import only numpy without the matlib , then Python will look for .matlib as an attribute of the numpy package. This attribute was not assigned to numpy without importing numpy.matlib (see discussion below)
Submodules and Binding
If you're wondering why np.matlib.identity works without using the npm keyword, this is because when you import the matlib submodule, the matlib parent module (named np in your case) will be assigned the matlib attribute attached to the submodule. This only works if you first define numpy .
From reference :
When a submodule is loaded using any mechanism (for example, importlib APIs, import or import statements, or built-in import ()), the binding is placed in the namespace of the parent modules on the submodule object.
Import and __init __. py
The choice of what you need to import is determined in the corresponding __init__.py module files in the module directory. You can use the dir() function to find out which names define the respective modules.
>> import numpy >> 'matlib' in dir(numpy)
Alternatively, if you look directly at the __init__.py file for numpy , you will not see the import for matlib .
Namespace for submodules
If you're curious how the namespace is copied seamlessly,
matlib source code runs this command to copy through the numpy namespace:
import numpy as np
Line (2), from numpy import * especially important. Because of this, you will notice that if you just import numpy.matlib , you can still use all numpy modules without importing numpy !
Without line (2), a copy of the namespace in line (3) will be bound only to the submodule. Interestingly, you can still make such a fun team because of the line (3).
import numpy.matlib numpy.matlib.np.matlib.np.array([1,1])
This is because np.__all__ bound to np numpy.matlib (which was imported on line (1)).