Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 425
ThR37 Avatar asked Nov 15 '22 09:11

ThR37


1 Answers

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.

like image 138
jchl Avatar answered Dec 14 '22 19:12

jchl