45

In the tutorial of the Cython documentation, there are cimport and import statements of numpy module:

import numpy as np
cimport numpy as np

I found this convention is quite popular among numpy/cython users.

This looks strange for me because they are both named as np. In which part of the code, imported/cimported np are used? Why cython compiler does not confuse them?

Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234
ywat
  • 2,757
  • 5
  • 24
  • 32
  • 2
    Because `cimport` doesn't really import a (Python) module. It imports [(C) definitions](http://docs.cython.org/src/userguide/sharing_declarations.html#the-cimport-statement). I don't know, but I could imagine that if you turn the second line into `cimport numpy` only, things would break: it may very well need the correspondonce between the actual Python module name as used in the script, and the definitions namespace. –  Nov 28 '13 at 14:18
  • 1
    @Evert You can also use `cimport numpy`, in the same way that one could use `import numpy`, it works just the same way, but `cimport` gives access to C functions or attributes under the imported module while `import` to Python functions or attributes – Saullo G. P. Castro Nov 28 '13 at 14:33

1 Answers1

50

cimport my_module gives access to C functions or attributes or even sub-modules under my_module

import my_module gives access to Python functions or attributes or sub-modules under my_module.

In your case:

cimport numpy as np

gives you access to Numpy C API, where you can declare array buffers, variable types and so on...

And:

import numpy as np

gives you access to NumPy-Python functions, such as np.array, np.linspace, etc

Cython internally handles this ambiguity so that the user does not need to use different names.

Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234
  • 2
    As a small addition: As hinted by @Saullo Castro, the Numpy C API does not offer all functions your Python Numpy offers. To find out what the C API can and can not do you can take a look at the `Includes` [folder](https://github.com/cython/cython/tree/master/Cython/Includes/numpy) in your Cython installation. There you will find the `.pxd` files Cython imports. – m00am Apr 18 '16 at 12:05
  • 1
    [Numpy C-API](https://docs.scipy.org/doc/numpy/reference/c-api.html) – gies0r May 17 '20 at 15:52