Internal python __dict__ for external C++ class?

Hi,

if I define a python class, then when I add member data to it, they are automatically entered into the class’ internal dictionary ‘dict’ and can be iterated over as follows:

>>> class myClass():
...     def __init__(self):
...             self.val1 = 0
...             self.val2 = 1
... 
>>> c = myClass()
>>> for key,value in c.__dict__.iteritems():
...     print key,value
... 
val2 1
val1 0

If I define an external C++ class, inheriting from TObject (so I can fill a TTree::Branch with the class data) and add data to this external class, the data are not automatically inserted into the internal dictionary:
MyClass.C

[code]class MyClass : public TObject
{
public:
int fMyInt1;
int fMyInt2;
int fMyInt3;

ClassDef(MyClass,1)
};

[/code]

>>> from ROOT import TFile, TTree 
>>> from ROOT import gROOT, AddressOf

>>> gROOT.ProcessLine(".L MyClass.C+")
   
>>> from ROOT import MyClass

>>> myClass = MyClass()
>>> file    = TFile('MyClass.root','RECREATE') 
>>> tree    = TTree('MyClass','Just A Tree') 
>>> tree.Branch("MyClass","MyClass",AddressOf(myClass))
            
>>> myClass.fMyInt1 = 1
>>> myClass.fMyInt2 = 2
>>> myClass.fMyInt3 = 3

>>> print repr(myClass.__dict__)
{}

However, if I add new data to the class from the python interpreter, that are not precompiled, these data are inserted into the internal dictionary

>>> myClass.fMyNewInt = 123
>>> print repr(myClass.__dict__)
{'fMyNewInt': 123}

My question is: is there a simple way to automatically add the data for the precompiled class to its internal dictionary?

Hi,

that wouldn’t work: if the instance level dictionary would have entries with the same name as the C++ public data members, they’d be hidden. In order to set a value on the C++ side, rather than keeping a reference on the python side only, a function needs to be called to convert and set the value. This is done in PyROOT by making the C++ data members descriptors on the python side. But, then they have to live at the class level (i.e., you’ll find them in MyClass.dict), as per the language specification.

Note that any new data member entries that you add to the myClass instance dict are invisible from the C++ side.

Cheers,
Wim

Okay, thanks for the prompt response.