Python C API: omitted variable assignment causes unexpected behaviour

亡梦爱人 提交于 2020-06-25 10:49:32

问题


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?

来源:https://stackoverflow.com/questions/25487199/python-c-api-omitted-variable-assignment-causes-unexpected-behaviour

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!