Import non-integer constant in .pyx file

后端 未结 1 1855
予麋鹿
予麋鹿 2021-01-22 21:24

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

相关标签:
1条回答
  • 2021-01-22 21:39

    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
    
    0 讨论(0)
提交回复
热议问题