Python C API: omitted variable assignment causes unexpected behaviour

273 Views Asked by At

While using python with pyroot (a python interface to a CERN data analysis package named ROOT), I encountered the following strange behaviour:

print ROOT.TFile(fname).GetListOfKeys()

outputs None while the seemingly semantically equivalent code

f=ROOT.TFile(fname)
print f.GetListOfKeys()

outputs the expected <ROOT.THashList object ("THashList") at 0x13f0fa0>.

While this is hardly the first bug I have encountered while working with ROOT, this time I am quite puzzled that python allows this bug to happen.

I reckon that somehow, the reference count for the TFile object gets wrong in the first example, and that it gets deleted before GetListOfKeys is actually called. (After setting ROOT.TFile.__del__ to be some print command, this is indeed what happens.)

The way I see it, after ROOT.TFile(fname) gets executed, but before GetListOfKeys() is called, the pointer to the TFile object is on the stack. Therefore, the reference count should not be zero and the destructor should not be called until GetListOfKeys() returns.

Can anyone shed some light on why this happens?

On a related note, is there a way to disable python from ever deling my objects implicitly just because the reference count becomes zero? I tried gc.disable(), and it did not change the results. Is there any more elegant solution than appending the objects to some globally defined write-only list?

0

There are 0 best solutions below