Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a static variable in a Python class via the C API?

Tags:

python

c

I want to do the equivalent of

class Foo(object):
  bar = 1

using Python's C API. In other words, I want to create a Python class which has a static variable, using C.

How can I do this?

like image 719
Vil Avatar asked Dec 23 '09 11:12

Vil


People also ask

How do you keep a variable static in Python?

A way to keep the static variables in sync is to make them properties: class Test(object): , _i = 3 , @property , def i(self) , return type(self).

How do you declare a static variable in Python class?

Python does not have a 'static' keyword to declare the static variable. In Python, you simply declare a variable inside the class, note that it should not be inside any method, and that variable will be known as a static or class variable.

How do you make a class variable static?

We can define class members static using static keyword. When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member. A static member is shared by all objects of the class.

Are static class variables possible in Python?

Practical Data Science using Python When we declare a variable inside a class but outside any method, it is called as class or static variable in python. Class or static variable can be referred through a class but not directly through an instance.


2 Answers

Found it! It's just a matter of setting the tp_dict element of the type object and filling adding entries to it for each of the static variables. The following C code creates the same static variable as the Python code above:

PyTypeObject type;
// ...other initialisation...
type.tp_dict = PyDict_New();
PyDict_SetItemString(type.tp_dict, "bar", PyInt_FromLong(1));
like image 137
Vil Avatar answered Sep 28 '22 04:09

Vil


You can pass that source code to Py_CompileString with the appropriate flags.

If you already have the class you could use PyObject_SetAttr.

like image 23
joeforker Avatar answered Sep 28 '22 04:09

joeforker