views:

77

answers:

2

Hello,

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.

A: 

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.

happy_emi
Thanks for your answer but, actually, the problem comes from the fact that I do not see any way to define a pair of set/get methods for the TypeObject itself : all that we can define is for the instances of the type.Thus, when I try to invoque myMod.A.x I get in my current version : <attribute 'x' of 'myMod.A' objects>I do not see the point of adding a field in the A_Object. I can easily access "x" by Acpp::x (that's what I do in the pair of getter/setter that are defined for the instances of the type object).
Elenaher
A: 

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.

jchl
Thank you for your answer. I think that I can indeed solve my problem by adding a field to tp_dict after the call to PyType_Ready.
Elenaher