Importing Libraries

Hi,

When we are importing ‘numpy’ then why do we have to import ‘linalg’ as “from numpy import linalg” ? Shouldn’t all be imported when we are importing ‘numpy’ ?

Thanks.

Hi. Abhinav!

You are right!

All the related functions will be loaded abstractly when import numpy. but if you specifically want to use any function then you want to import it for pointing it to access all the functionality of it, it is just object level reference.

Otherwise if every function is activated then it will take all your memory!
You can find all the related functions of numpy using dir(numpy).

All the best!

1 Like

I don’t know why wasn’t it working at the time i was trying, had to write both:

import numpy as np
from numpy import linalg

Maybe i should’ve restarted the kernel.

Thanks! :slight_smile:

Hi,

It has all to do with the namespace.

  • If you use import numpy , all sub-modules and functions in the numpy module can only be accesses in the numpy.* namespace. For example numpy.array([1,2,3]) .
  • If you use import numpy as np , an alias for the namespace will be created. For example np.array([1,2,3]) .
  • If you use from numpy import * , all functions will be loaded into the local namespace. For example array([1,2,3]) can then be used.

The latter is not advisable, since it may result in ‘overlapping’ function names, where the latest imported function holds the position in memory. For example from math import * will override the default pow function, removing the ability to use pow(x, y, m) . Although, sometimes it might be useful to load functions into the local namespace, please try to do that only in the interactive shell and preferably for selected functions, e.g. from numpy import array, vectorize, dot .

Thanks!

  1. from numpy import * or import numpy as np
    =============================================

Here np act just like alias to numpy so that we should not write numpy keyword of 5 length again and again , will import all the sub modules implemented as python files in the current local namespace. then no need to create any alias direct numpy.(any_module_name) but this will create lot of functions in namespace. as python need to resolve which module you are using from numpy package.
It will search for all the function in the list and time complexity is O(len(numpylist)).

  1. But, if you from numpy import linalg
    =====================================
    it will just point to the linalg module directly with constant time and access will be easier with constant time complexity. .
    and in the namespace also this linalg module will be stored and it will be cleaner. and will take lesser memory also. as you are just referring to the specific function only.
    ]
    Kindly find the numpy ndarray and linalg array that you will use in the list below.,

[‘ALLOW_THREADS’,
‘AxisError’,
‘BUFSIZE’,
‘CLIP’,
‘ComplexWarning’,
‘DataSource’,
‘ERR_CALL’,
‘ERR_DEFAULT’,
‘ERR_IGNORE’,
‘ERR_LOG’,
‘ERR_PRINT’,
‘ERR_RAISE’,
‘ERR_WARN’,
‘FLOATING_POINT_SUPPORT’,
‘FPE_DIVIDEBYZERO’,
‘FPE_INVALID’,
‘FPE_OVERFLOW’,
‘FPE_UNDERFLOW’,
‘False_’,
‘Inf’,
‘Infinity’,
‘MAXDIMS’,
‘MAY_SHARE_BOUNDS’,
‘MAY_SHARE_EXACT’,
‘MachAr’,
‘ModuleDeprecationWarning’,
‘NAN’,
‘NINF’,
‘NZERO’,
‘NaN’,
‘PINF’,
‘PZERO’,
‘RAISE’,
‘RankWarning’,
‘SHIFT_DIVIDEBYZERO’,
‘SHIFT_INVALID’,
‘SHIFT_OVERFLOW’,
‘SHIFT_UNDERFLOW’,
‘ScalarType’,
‘Tester’,
‘TooHardError’,
‘True_’,
‘UFUNC_BUFSIZE_DEFAULT’,
‘UFUNC_PYVALS_NAME’,
‘VisibleDeprecationWarning’,
‘WRAP’,
NoValue’,
UFUNC_API’,
NUMPY_SETUP’,
all’,
builtins’,
cached’,
config’,
doc’,
file’,
git_revision’,
loader’,
mkl_version’,
name’,
package’,
path’,
spec’,
version’,
add_newdoc_ufunc’,
arg’,
distributor_init’,
globals’,
mat’,
mklinit’,
pytesttester’,
‘abs’,
‘absolute’,
‘absolute_import’,
‘add’,
‘add_docstring’,
‘add_newdoc’,
‘add_newdoc_ufunc’,
‘alen’,
‘all’,
‘allclose’,
‘alltrue’,
‘amax’,
‘amin’,
‘angle’,
‘any’,
‘append’,
‘apply_along_axis’,
‘apply_over_axes’,
‘arange’,
‘arccos’,
‘arccosh’,
‘arcsin’,
‘arcsinh’,
‘arctan’,
‘arctan2’,
‘arctanh’,
‘argmax’,
‘argmin’,
‘argpartition’,
‘argsort’,
‘argwhere’,
‘around’,
‘array’,
‘array2string’,
‘array_equal’,
‘array_equiv’,
‘array_repr’,
‘array_split’,
‘array_str’,
‘asanyarray’,
‘asarray’,
‘asarray_chkfinite’,
‘ascontiguousarray’,
‘asfarray’,
‘asfortranarray’,
‘asmatrix’,
‘asscalar’,
‘atleast_1d’,
‘atleast_2d’,
‘atleast_3d’,
‘average’,
‘bartlett’,
‘base_repr’,
‘binary_repr’,
‘bincount’,
‘bitwise_and’,
‘bitwise_not’,
‘bitwise_or’,
‘bitwise_xor’,
‘blackman’,
‘block’,
‘bmat’,
‘bool’,
‘bool8’,
'bool
’,
‘broadcast’,
‘broadcast_arrays’,
‘broadcast_to’,
‘busday_count’,
‘busday_offset’,
‘busdaycalendar’,
‘byte’,
‘byte_bounds’,
‘bytes0’,
'bytes
’,
'c
’,
‘can_cast’,
‘cast’,
‘cbrt’,
‘cdouble’,
‘ceil’,
‘cfloat’,
‘char’,
‘character’,
‘chararray’,
‘choose’,
‘clip’,
‘clongdouble’,
‘clongfloat’,
‘column_stack’,
‘common_type’,
‘compare_chararrays’,
‘compat’,
‘complex’,
‘complex128’,
‘complex256’,
‘complex64’,
'complex
’,
‘complexfloating’,
‘compress’,
‘concatenate’,
‘conj’,
‘conjugate’,
‘convolve’,
‘copy’,
‘copysign’,
‘copyto’,
‘core’,
‘corrcoef’,
‘correlate’,
‘cos’,
‘cosh’,
‘count_nonzero’,
‘cov’,
‘cross’,
‘csingle’,
‘ctypeslib’,
‘cumprod’,
‘cumproduct’,
‘cumsum’,
‘datetime64’,
‘datetime_as_string’,
‘datetime_data’,
‘deg2rad’,
‘degrees’,
‘delete’,
‘deprecate’,
‘deprecate_with_doc’,
‘diag’,
‘diag_indices’,
‘diag_indices_from’,
‘diagflat’,
‘diagonal’,
‘diff’,
‘digitize’,
‘disp’,
‘divide’,
‘division’,
‘divmod’,
‘dot’,
‘double’,
‘dsplit’,
‘dstack’,
‘dtype’,
‘e’,
‘ediff1d’,
‘einsum’,
‘einsum_path’,
‘emath’,
‘empty’,
‘empty_like’,
‘equal’,
‘errstate’,
‘euler_gamma’,
‘exp’,
‘exp2’,
‘expand_dims’,
‘expm1’,
‘extract’,
‘eye’,
‘fabs’,
‘fastCopyAndTranspose’,
‘fft’,
‘fill_diagonal’,
‘find_common_type’,
‘finfo’,
‘fix’,
‘flatiter’,
‘flatnonzero’,
‘flexible’,
‘flip’,
‘fliplr’,
‘flipud’,
‘float’,
‘float128’,
‘float16’,
‘float32’,
‘float64’,
'float
’,
‘float_power’,
‘floating’,
‘floor’,
‘floor_divide’,
‘fmax’,
‘fmin’,
‘fmod’,
‘format_float_positional’,
‘format_float_scientific’,
‘format_parser’,
‘frexp’,
‘frombuffer’,
‘fromfile’,
‘fromfunction’,
‘fromiter’,
‘frompyfunc’,
‘fromregex’,
‘fromstring’,
‘full’,
‘full_like’,
‘fv’,
‘gcd’,
‘generic’,
‘genfromtxt’,
‘geomspace’,
‘get_array_wrap’,
‘get_include’,
‘get_printoptions’,
‘getbufsize’,
‘geterr’,
‘geterrcall’,
‘geterrobj’,
‘gradient’,
‘greater’,
‘greater_equal’,
‘half’,
‘hamming’,
‘hanning’,
‘heaviside’,
‘histogram’,
‘histogram2d’,
‘histogram_bin_edges’,
‘histogramdd’,
‘hsplit’,
‘hstack’,
‘hypot’,
‘i0’,
‘identity’,
‘iinfo’,
‘imag’,
‘in1d’,
‘index_exp’,
‘indices’,
‘inexact’,
‘inf’,
‘info’,
‘infty’,
‘inner’,
‘insert’,
‘int’,
‘int0’,
‘int16’,
‘int32’,
‘int64’,
‘int8’,
'int
’,
‘int_asbuffer’,
‘intc’,
‘integer’,
‘interp’,
‘intersect1d’,
‘intp’,
‘invert’,
‘ipmt’,
‘irr’,
‘is_busday’,
‘isclose’,
‘iscomplex’,
‘iscomplexobj’,
‘isfinite’,
‘isfortran’,
‘isin’,
‘isinf’,
‘isnan’,
‘isnat’,
‘isneginf’,
‘isposinf’,
‘isreal’,
‘isrealobj’,
‘isscalar’,
‘issctype’,
'issubclass
’,
‘issubdtype’,
‘issubsctype’,
‘iterable’,
'ix
’,
‘kaiser’,
‘kron’,
‘lcm’,
‘ldexp’,
‘left_shift’,
‘less’,
‘less_equal’,
‘lexsort’,
‘lib’,
’linalg’,
‘linspace’,
‘little_endian’,
‘load’,
‘loads’,
‘loadtxt’,
‘log’,
‘log10’,
‘log1p’,
‘log2’,
‘logaddexp’,
‘logaddexp2’,
‘logical_and’,
‘logical_not’,
‘logical_or’,
‘logical_xor’,
‘logspace’,
‘long’,
‘longcomplex’,
‘longdouble’,
‘longfloat’,
‘longlong’,
‘lookfor’,
‘ma’,
‘mafromtxt’,
‘mask_indices’,
‘mat’,
‘math’,
‘matmul’,
‘matrix’,
‘matrixlib’,
‘max’,
‘maximum’,
‘maximum_sctype’,
‘may_share_memory’,
‘mean’,
‘median’,
‘memmap’,
‘meshgrid’,
‘mgrid’,
‘min’,
‘min_scalar_type’,
‘minimum’,
‘mintypecode’,
‘mirr’,
‘mod’,
‘modf’,
‘moveaxis’,
‘msort’,
‘multiply’,
‘nan’,
‘nan_to_num’,
‘nanargmax’,
‘nanargmin’,
‘nancumprod’,
‘nancumsum’,
‘nanmax’,
‘nanmean’,
‘nanmedian’,
‘nanmin’,
‘nanpercentile’,
‘nanprod’,
‘nanquantile’,
‘nanstd’,
‘nansum’,
‘nanvar’,
‘nbytes’,
’ndarray’,
‘ndenumerate’,
‘ndfromtxt’,
‘ndim’,
‘ndindex’,
‘nditer’,
‘negative’,
‘nested_iters’,
‘newaxis’,
‘nextafter’,
‘nonzero’,
‘not_equal’,
‘nper’,
‘npv’,
’numarray’,
‘number’,
‘obj2sctype’,
‘object’,
‘object0’,
'object
’,
‘ogrid’,
‘oldnumeric’,
‘ones’,
‘ones_like’,
‘outer’,
‘packbits’,
‘pad’,
‘partition’,
‘percentile’,
‘pi’,
‘piecewise’,
‘place’,
‘pmt’,
‘poly’,
‘poly1d’,
‘polyadd’,
‘polyder’,
‘polydiv’,
‘polyfit’,
‘polyint’,
‘polymul’,
‘polynomial’,
‘polysub’,
‘polyval’,
‘positive’,
‘power’,
‘ppmt’,
‘print_function’,
‘printoptions’,
‘prod’,
‘product’,
‘promote_types’,
‘ptp’,
‘put’,
‘put_along_axis’,
‘putmask’,
‘pv’,
‘quantile’,
‘r_’,
‘rad2deg’,
‘radians’,
‘random’,
‘rank’,
‘rate’,
‘ravel’,
‘ravel_multi_index’,
‘real’,
‘real_if_close’,
‘rec’,
‘recarray’,
‘recfromcsv’,
‘recfromtxt’,
‘reciprocal’,
‘record’,
‘remainder’,
‘repeat’,
‘require’,
‘reshape’,
‘resize’,
‘result_type’,
‘right_shift’,
‘rint’,
‘roll’,
‘rollaxis’,
‘roots’,
‘rot90’,
‘round’,
‘round_’,
‘row_stack’,
‘s_’,
‘safe_eval’,
‘save’,
‘savetxt’,
‘savez’,
‘savez_compressed’,
‘sctype2char’,
‘sctypeDict’,
‘sctypeNA’,
‘seterr’,
‘seterrcall’,
‘seterrobj’,
‘setxor1d’,
‘shape’,
‘shares_memory’,
‘short’,

‘str’,
‘str0’,
‘str_’,
‘string_’,
‘subtract’,
‘sum’,
‘swapaxes’,
‘sys’,
‘take’,
‘take_along_axis’,
‘tan’,
‘tanh’,
‘tensordot’,
‘test’,
‘testing’,
‘tile’,
‘timedelta64’,
‘trace’,
‘tracemalloc_domain’,
‘transpose’,
‘trapz’,
‘tri’,
‘tril’,
‘unique’,
‘unpackbits’,
‘unravel_index’,
‘unsignedinteger’,
‘unwrap’,
‘ushort’,
‘vander’,
‘var’,

‘zeros_like’]