Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Variables in Python C API

How would one expose "static" variables like this

class MyClass:
    X = 1
    Y = 2

via the C API? The only variable on the PyTypeObject that looks like it would work is tp_members, but I see no flag in the PyMemberDef to indicate that the member should be per-class, not per-instance.

For a bit more clarification, since it may change the answer, I'm trying to expose a C enum to Python such that the enumeration

enum MyFlags {
    Alpha = 0,
    Beta = 1
};

Can be accessed in Python as:

module.MyFlags.Alpha
module.MyFlags.Beta
like image 583
Toji Avatar asked Mar 03 '10 19:03

Toji


People also ask

How do you declare a static variable in 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.

What is static variable in C?

Static variables are initialized only once. The compiler persists with the variable till the end of the program. Static variables can be defined inside or outside the function. They are local to the block. The default value of static variables is zero.

How do you use static in Python?

The Python approach is simple; it doesn't require a static keyword. All variables which are assigned a value in the class declaration are class variables. And variables that are assigned values inside methods are instance variables.

How do you view a static variable in Python?

To access the static variable inside the static method, then we have to use @staticmethod decorator, and then we can access it by using classname. To access the static variable outside the class by using either object reference or by using the class name.


1 Answers

Just put them in the type's tp_dict e.g. with PyDict_SetItemString.

like image 190
Alex Martelli Avatar answered Oct 30 '22 05:10

Alex Martelli