Difference between import numpy and import numpy as np

后端 未结 5 613
说谎
说谎 2021-01-31 16:09

I understand that when possible one should use

import numpy as np

This helps keep away any conflict due to namespaces. But I have noticed that

5条回答
  •  死守一世寂寞
    2021-01-31 17:00

    The import as syntax was introduced in PEP 221 and is well documented there.

    When you import a module via

    import numpy
    

    the numpy package is bound to the local variable numpy. The import as syntax simply allows you to bind the import to the local variable name of your choice (usually to avoid name collisions, shorten verbose module names, or standardize access to modules with compatible APIs).

    Thus,

    import numpy as np
    

    is equivalent to,

    import numpy
    np = numpy
    del numpy
    

    When trying to understand this mechanism, it's worth remembering that import numpy actually means import numpy as numpy.

    When importing a submodule, you must refer to the full parent module name, since the importing mechanics happen at a higher level than the local variable scope. i.e.

    import numpy as np
    import numpy.f2py   # OK
    import np.f2py      # ImportError
    

    I also take issue with your assertion that "where possible one should [import numpy as np]". This is done for historical reasons, mostly because people get tired very quickly of prefixing every operation with numpy. It has never prevented a name collision for me (laziness of programmers actually suggests there's a higher probability of causing a collision with np)

    Finally, to round out my exposé, here are 2 interesting uses of the import as mechanism that you should be aware of:

    1. long subimports

    import scipy.ndimage.interpolation as warp
    warp.affine_transform(I, ...)
    

    2. compatible APIs

    try:
        import pyfftw.interfaces.numpy_fft as fft
    except:
        import numpy.fft as fft
    # call fft.ifft(If) with fftw or the numpy fallback under a common name
    

提交回复
热议问题