ThR37
ThR37

Reputation: 4085

Python API C++ : "Static variable" for a Type Object

I have a small question about static variable and TypeObjects. I use the API C to wrap a c++ object (let's call it Acpp) that has a static variable called x. Let's call my TypeObject A_Object :

typedef struct {
  PyObject_HEAD
  Acpp* a;
} A_Object;

The TypeObject is attached to my python module "myMod" as "A". I have defined getter and setters (tp_getset) so that I can access and modify the static variable of Acpp from python :

>>> import myMod
>>> myA1 = myMod.A(some args...)
>>> myA1.x = 34 # using the setter to set the static variable of Acpp
>>> myA2 = myMod.A(some other args...)
>>> print myA2.x
34
>>> # Ok it works !

This solution works but it's not really "clean". I would like to access the static variable in python by using the TypeObject and not the instances :

>>> import myMod
>>> myMod.A.x = 34 # what I wish...

Does anybody have an idea to help me ?

Thanks in advance.

Upvotes: 5

Views: 345

Answers (2)

jchl
jchl

Reputation: 6532

Essentially, what you're trying to do is define a "static property". That is, you want a function to be called when you get/set an attribute of the class.

With that in mind, you might find this thread interesting. It only talks about Python-level solutions to this problem, not C extension types, but it covers the basic principles.

To implement the solution proposed in that thread for a C extension type, I think you'd have to initialize tp_dict and add to it an entry for "x" whose value is an object that implements __get__ appropriately.

Upvotes: 1

Emiliano
Emiliano

Reputation: 23752

You could add a dummy 'x' field in the A_Object and create a pair of set/get methods. When you access the dummy 'x' field, the method would redirect the call to the static 'x' field.

Upvotes: 0

Related Questions