Attila49
Attila49

Reputation: 59

Need help for understanding Cython -find an example but doesn't working

I have a problem for understanding Cython and pxd. I have find this code on internet but doesn't working. Can you explain me why ?

The error when I compile:

warning: test.pyx:1:0: Overriding cdef method with def method.

test.pxd:6:14: C method 'foo' is declared but not defined

I find this example here : https://cython.readthedocs.io/en/latest/src/tutorial/pure.html

I have do an error into the compilation ?

compile.py :

import os
import sysconfig

from distutils.core import setup
from Cython.Build import cythonize

fichier = "test.pyx"

setup(
    ext_modules = cythonize(fichier)
)

test.pyx :

def myfunction(x, y=2):
    a = x - y
    return a + x * y

def _helper(a):
    return a + 1

class A:
    def __init__(self, b=0):
        self.a = 3
        self.b = b

    def foo(self, x):
        print(x + _helper(1.0))

test.pxd :

cpdef int myfunction(int x, int y=*)
cdef double _helper(double a)

cdef class A:
    cdef public int a, b
    cpdef foo(self, double x)

Upvotes: 0

Views: 220

Answers (1)

DavidW
DavidW

Reputation: 30913

This is to do with the filename. .pyx files are dealt with as Cython files (i.e. they have to match the .pxd files). However .py files are interpreted as "pure Python mode" (since they also have to work in Python).

If you rename your .pyx file to .py it will work.


This is stated pretty clearly in the documentation you linked to:

While declarations in a .pyx file must correspond exactly with those of a .pxd file with the same name (and any contradiction results in a compile time error, see pxd files), the untyped definitions in a .py file can be overridden and augmented with static types by the more specific ones present in a .pxd

Upvotes: 1

Related Questions