I am working with Cython and numpy, and have a strange issue to do with a cython function changing the dtype of the elements of a numpy array. Strangely, the dtype is only changed when the input type of the array is actually specified.
I am using Cython==0.29.11, numpy==1.15.4, python 3.6, on Ubuntu 18.04.
# cyth.pyx
cimport numpy as np
def test(x):
print(type(x[0]))
def test_np(np.ndarray[np.uint32_t, ndim=1] x):
print(type(x[0]))
Now cythonising this file and using the functions:
>>> from cyth import test, test_np
>>> import numpy as np
>>> a = np.array([1, 2], dtype=np.uint32)
>>> test(a)
<class 'numpy.uint32'>
>>> test_np(a)
<class 'int'>
So test works as expected, printing the type of the first element in the input array - a uint32. But test_np, which actually ensures that the type of the incoming array is uint32, now shows a regular Python int as the type of the first element.
Even trying to force the element to to be of the right type does not work, i.e. using:
def test_np(np.ndarray[np.uint32_t, ndim=1] x):
cdef np.uint32_t el
el = x[0]
print(type(el))
still results in
>>> test_np(a)
<class 'int'>
Any help in understanding this discrepancy would be greatly appreciated.