0

I'm attempting to build a Python C extension using Cython. The problem is that when I structure the project in submodules, the defined objects in Cython are no longer available.

This is a simple project that I created to reproduce the issue I'm having:

├── foo
│   ├── bar
│   │   ├── bar.pyx
│   │   ├── cbar.pxd
│   │   ├── __init__.py
│   ├── __init__.py
├── setup.py
└── src
    ├── bar.c
    └── bar.h

And this is the setup.py:

from setuptools import Extension, setup
from Cython.Build import cythonize

ext_modules = [
  Extension("foo.bar", ["foo/bar/bar.pyx"]),
]

setup(
  ext_modules=cythonize(ext_modules, language_level=3),
  packages=["foo", "foo.bar"]
)

The pyx file is quite simple

# distutils: sources = src/bar.c
# distutils: include_dirs = src/

cimport foo.bar.cbar as s

cdef class Foobar:
  cdef int number

  def __cinit__(self):
    self.number = 357

  def double(self):
    return s.double_int(self.number)

But when installing with

python setup.py build_ext --inplace

and running a shell to import and try it:

>>> import foo
>>> dir(foo)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'bar', 'foo']
>>> dir(foo.bar)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__']
>>> 

There's no Foobar class available in foo.bar. Also, I don't really know why "foo" is a submodule of itself. Would appreciate any help! Thanks!

popeye
  • 81
  • 2
  • 5
  • It'd be a little easier to debug this if I didn't have to rebuild the project manually, maybe a link to a git repo I can clone would be nice? – ngoldbaum Dec 22 '22 at 21:29
  • Thanks for taking interest! The solution was quite simple: the extension module being built should not have the same name as the submodule (bar in this case) – popeye Dec 27 '22 at 00:50

0 Answers0