How can I declare constants (of various types - not just enum values) and share them between multiple .pyx
files?
Within a .pyx
file, I can dec
You could use a very short inline function (in the pxd file) that just returns the constant
cdef inline const char* GetFavouriteFood():
return "spam"
cdef inline float GetHowMuch():
return 4.5
The other option would be to define the constants in C in a header file then (in your pxd) do
cdef extern from "myconstants.h":
const char* FavouriteFood
float HowMuch
The C compiler (rather than Cython) enforces the constness so errors will appear at that stage if you try to change them. This does involve create an extra file so personally I prefer the inline function approach.
Edit (2018):
You can now include C code directly in Cython which makes the second approach easier:
cdef extern from *:
"""const char* FavouriteFood = "spam";
const float HowMuch = 4.5;"""
const char* FavouriteFood
float HowMuch