Chuck Chuck - 10 months ago 46
Python Question

Is Cython used for building C code or is it used for building Python extensions?

I am the sole Matlab user on a team of C++/C# developers. I am transitioning to Python, and was hoping that Cython could help me bridge the gap between my work and my colleagues' work.

I originally thought that Cython could be used to compile Python code to a C source file, which could then be imported/called from Python. I was hoping for two benefits from this:

  1. A speed boost in my programs, and

  2. A C source file that could be handed off to my colleagues for some slight polishing and then ultimately implemented in their (C++/C#) packages.

Unfortunately, it looks like the latter is not an option, but I'm not positive. It looks like the C source file is very bloated with lots of references to Python. I have a three-line Python script that declares a cdef char*, assigns the string "hello world!" to that variable, then prints it. The resulting C file is 2000 lines long.

So, my question is, is benefit #2 unobtainable with Cython? Is the C code generated with Cython only intended to be used by Python, or is there a way to remove the Python bloat and get a concise C translation of the Python code?

Answer Source

Cython's output is not intended for human consumption

Cython treats C as an intermediate language, in much the same way as LLVM treats LLVM IR as an intermediate language. Cython's purpose is to produce Python extension modules, and C is just the most reasonable means to that end. It will generally produce a maze of twisty little preprocessor directives, all totally unreadable. You should not use Cython if you want C code that you can read.