Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cython: cimport and import numpy as (both) np

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?

like image 337
ywat Avatar asked Nov 28 '13 14:11

ywat


People also ask

Can you use NumPy with Cython?

You can use NumPy from Cython exactly the same as in regular Python, but by doing so you are losing potentially high speedups because Cython has support for fast access to NumPy arrays.

Does Cython improve NumPy?

By explicitly declaring the "ndarray" data type, your array processing can be 1250x faster. This tutorial will show you how to speed up the processing of NumPy arrays using Cython. By explicitly specifying the data types of variables in Python, Cython can give drastic speed increases at runtime.

What is Cimport Cython?

The cimport statement is used in a definition or implementation file to gain access to names declared in another definition file. Its syntax exactly parallels that of the normal Python import statement. When pure python syntax is used, the same effect can be done by importing from special cython.


1 Answers

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.

like image 171
Saullo G. P. Castro Avatar answered Sep 20 '22 08:09

Saullo G. P. Castro