Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a static member to a Cython class (from python, not C)

How would I add a static, typed member to a cython class? The syntax for adding typed instance-members uses the syntax as follows (e.g.):

import cython

cdef class NoStaticMembers:

   cdef public int instanceValue # but, how do I create a static member??

   def __init__(self, int value):
       self.instanceValue = value
like image 229
user27886 Avatar asked Mar 13 '15 06:03

user27886


People also ask

Does Python have static members?

Yes, definitely possible to write static variables and methods in python. Static Variables : Variable declared at class level are called static variable which can be accessed directly using class name.

How do you create a static member?

Note: To create a static member(block, variable, method, nested class), precede its declaration with the keyword static. When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object.

What is static member in Python?

Static means, that the member is on a class level rather on the instance level. Static variables exist only on class level and aren't instantiated. If you change a static variable in one instance of the class, the change will affect its value in all other instances.


1 Answers

Just because you can do it in C really doesn't mean you can do it in Cython.

A workround might involve using global variables, and class properties so you can access them through class instances. I'm not sure if it's really better than using global variables though

import cython

cdef int MyClass_static_variable

cdef class MyClass:
   property static_variable:
      def __get__(self):
         return MyClass_static_variable

      def __set__(self, x):
         global MyClass_static_variable
         MyClass_static_variable = x

You'd have to measure how much speed you lost through that method (and maybe consider making __get__ and __set__ cpdef if you can - I'm not sure). The only thing that doesn't let you do that a genuine static variable does is to access it as MyClass.static_variable.

like image 123
DavidW Avatar answered Oct 21 '22 18:10

DavidW