I'm using Cython to wrap a C library. The C library's header file defines a number of constants, so in my cython module, I have something like:
cdef extern from "lib.h":
cdef int CONST_A = 0
cdef int CONST_B = 1
When I compile the extension, the constants are not available in Python. I tried doing something like this, but it did not seem to work:
cdef extern from "lib.h":
cdef int CONST_A = 0
cdef int CONST_B = 1
CONST_A = CONST_A
CONST_B = CONST_B
Any ideas on how to make these constants available in Python?
You're right in that there seems to be a hole in Cython there.
I can declare cpdef int CONST_C = 3
and it compiles but isn't visible from Python. That would seem to be a bug -- if it accepts the syntax, it should do something reasonable with it.
One thing that did seem to work is this:
cpdef enum:
CONST_A = 0
CONST_B = 1
That may or may not be good enough for your case, but it seems it would work well for many use-cases -- maybe it's why the bug wasn't noticed?
The solution I use which would be fairly easy to then switch to the "right" solution once supported is to re-declare the enum values one by one in the .pyx file prefixed by the enum's name, then they are quite easy to spot.
So in foo.pxd:
cdef enum Mood:
happy
sad
Then in foo.pyx at global scope:
Mood_happy = happy
Mood_sad = sad
And in bar.py:
from foo import Mood_happy, Mood_sad
# do something with Mood_happy and Mood_sad as ints
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With