pythoncythonpython-c-apicythonize

Cython module property


In Cython, you can define getter and setter functions for class properties:

cdef class module
  property a:
    def __get__(self):
      cdef int a
      get_a(&a)
      return a
    def __set__(self, int a):
      set_a(&a)

Is there a way to define getters and setters at the module level? For example, the syntax might look something like this.

@module_property
def a():
  pass
  
@a.setter
def a(int new_a):
  set_a(&new_a)
  
@a.getter
def a():
  cdef int a_copy
  get_a(&a_copy)
  return a_copy

Solution

  • As @Brian pointed out, a global instance of a class works great. So it might look something like:

    cdef class module: 
      property a:
        def __get__(self):
          cdef int a_copy
          get_a(&a_copy)
          return a
        def __set__(self, int new_a):
          set_a(&new_a)
          
    module_instance = module()