3

I know how to make C code from Python using cythonize -o mymodule.c mymodule.py or using the cython command. The resulting C file has to be compiled to an Python extension using gcc or any other C compiler, and I'm also able doing that. If I want it really simple, I just use distutils/setuptools and python setup.py build_ext.

But what I can't figure out is how to make an extension file (pyd/so) with a DIFFERENT name than the source file. I can't simply rename the file due to the fact that there has to be a function PyInit_modulename in the extension, and I can't change modulename.pyd to _modulename.pyd, that would require PyInit__modulename and throw this exeption:

ImportError: dynamic module does not define init function (PyInit__modulename)

Basically it should be like this:

mymodule.py -> _mymodule.pyd

This avoids e.g. the import confusion if I have two files with the same name but a different ending (py/pyd/pyc/pyo/so/dll):

mydir/
  mymodule.py
  mymodule.pyd

Code:

from mymodule import func
func()
# Is this now from the extension or from the python code?
# And how to access tho other one?

What I need is:

mydir/
  mymodule.py
  _mymodule.pyd   <- Note the underscore!

Code:

import mymodule as script
script.func()
# Run the code from the python file

import _mymodule as extension
extension.func()
# Run code from the extension

But how on earth can I compile like this?

Thank you in advance!


Just one thought I had: I think I need to start somewhere at the C code generation with cython.

linusg
  • 6,289
  • 4
  • 28
  • 78
  • 1
    It seems that the only way to affect the module name is by changing the name of the cython file i.e. `_modulename.pyx`. – J.J. Hakala Jul 11 '16 at 17:29
  • @J.J.Hakala - Yes, I already thought that after some days of research. I made a script for that, wich automatically saves the file in the temp dir to a given name and compiles the file – linusg Jul 11 '16 at 18:13

1 Answers1

-1

Try this in your setup.py

try:
    from setuptools import setup
    from setuptools import Extension
except ImportError:
    from distutils.core import setup
    from distutils.extension import Extension

from Cython.Distutils import build_ext
import numpy as np # if it requires numpy

ext_modules = [Extension("desired_name",["original_name.pyx"])]

setup(
    name= 'Generic model class',
    cmdclass = {'build_ext': build_ext},
    include_dirs = [np.get_include()], # only if it requires numpy
    ext_modules = ext_modules)
sebacastroh
  • 608
  • 4
  • 13
  • 1
    That doesn't not work, it throws an Import error due to the missing PyInit_original_name function. I already tried this before, it would be too easy! – linusg Jul 06 '16 at 19:45