Cython- import class to pyx file

274 Views Asked by At

For example let's say we have two classe,

Bus- Implement The physical bus line.

src/bus/bus.pxd

   cdef class Bus:
        cdef int get_item(self)

src/bus/bus.pxd:

cdef class Bus: 
    cdef int get_item(self):
        return 5

CPU- Implement The physical cpu processor

src/cpu/cpu.pyx:

cimport bus.Bus as Bus
cdef class Cpu:
     cdef Bus bus
     cdef __cinit__(self, Bus bus):
         self.bus = bus

setup.py:

from setuptools import setup, Extension
import sys
import numpy 

USE_CYTHON = False

files = [
    ('src.bus', 'src/bus/bus'),
    ('src.cpu', 'src/cpu/cpu'),
] 

if '--use-cython' in sys.argv:
    USE_CYTHON = True
    sys.argv.remove('--use-cython')
   
ext = '.pyx' if USE_CYTHON else '.c'


extensions = []
for package_path, file_path in files:
    extensions.append(
        Extension(package_path,[f"{file_path}{ext}"],
                        language='c',
                        include_dirs=['src/c/'])
    )

if USE_CYTHON:
    from Cython.Build import cythonize
    extensions = cythonize(extensions)

setup(
    ext_modules=extensions,
    include_dirs=[numpy.get_include()]
) 

However, when compiling this example the compiler raise error of 'Bus' is not a type identifier. Any suggestion?

1

There are 1 best solutions below

1
On

So, in cython we've to use pxd file for declaration in compile time. Therefor, adding __init__.pxd have to bee added for compilation import. In Addition, I've created cpu.pxd file which inside I've wrote from bus cimport Bus.