ko samuel
ko samuel

Reputation: 27

Cython Python: Previous declaration is here when i construct __init__ of a class

I am a newbie to Cython, the code below is to initialize a class A:

a.pyx

from __future__ import division
cimport cython
from libcpp cimport bool
cimport numpy as np
import numpy as np

DTYPE = np.float64
ctypedef np.float64_t DTYPE_t
TTYPE = np.int64
ctypedef np.int64_t TTYPE_t


cdef class A():
    @cython.boundscheck(False)
    @cython.wraparound(False)
    def __init__(self, np.ndarray[DTYPE_t, ndim=2, mode='c'] _cost_matrix):
        cdef np.ndarray[DTYPE_t, ndim=2] _cost_matrix = np.atleast_2d(_cost_matrix)
        ...

The error is Error compiling Cython file:

------------------------------------------------------------


    @cython.boundscheck(False)
    @cython.wraparound(False)
    def __init__(self, np.ndarray[DTYPE_t, ndim=2, mode='c'] _cost_matrix):

linear_assignment_cython.pyx:72:23: Previous declaration is here
Traceback (most recent call last):                      
------------------------------------------------------------

setup.py

# coding: UTF-8
"""
    @author: samuel ko
"""
from distutils.core import setup
from Cython.Build import cythonize
import numpy

setup(
    name="haha",
    ext_modules=cythonize("a.pyx"),
    include_dirs=[numpy.get_include()],
)

I wonder the position of include_dirs of numpy need to be explicity pointed of absolute dirs?

The dir of my numpy core path is: /usr/local/lib/python3.6/dist-packages/numpy/core/include and i have change it to replace numpy.get_include() but still not work.

Really hope your kindness help, thank you very much ^.^~

Upvotes: 0

Views: 582

Answers (1)

DavidW
DavidW

Reputation: 30917

You've defined _cost_matrix twice. Once as a function input and once as a local variable. The second assignment (after np.atleast_2d) is pointless, because you've already ensured that the function input is a 2D array.

You might be better doing:

def __init__(self, _cost_matrix_in): # untyped variable in, different name
    # then ensure it's 2D and enforce the type.
    cdef np.ndarray[DTYPE_t, ndim=2] _cost_matrix = np.atleast_2d(_cost_matrix)

Upvotes: 1

Related Questions