Saving a python dict of TObjects in a class

hi all

i’m having problems trying to create a python class that keeps a map of TObjects (in this case TH1F’s) saved as a data member.

i’m attaching two python scripts:

  • test.py has no problems running
  • testClass.py should in principle do the same exact thing but crashes after printing “x2”:

$ python testClass.py
x1
100
x2
Traceback (most recent call last):
File “testClass.py”, line 36, in
d = dummyClass(“pdfQG_AK4chs_13TeV.root”)
File “testClass.py”, line 14, in init
print self.pdfs[“axis2_quark_eta-0_pt-11_rho-18”].GetNbinsX()
AttributeError: ‘PyROOT_NoneType’ object has no attribute ‘GetNbinsX’

i must be doing something wrong with ROOT memory handling, but i’m not a pyROOT expert, so i’m not sure how i should do this

any ideas?

thanks
f
testClass.py (719 Bytes)
test.py (383 Bytes)

Hi Francesco,

the problem is that the TFile goes out of scope and the histograms you put in the dictionary are attached to it, even after the clone.
The solution, one of the many but I decided to stick to your example, could be:

from ROOT import *
class dummyClass :
  def __init__(self, filename) :
    self.pdfs = {}
    self.init(filename)
    print "x2"
    print self.pdfs["axis2_quark_eta-0_pt-11_rho-18"].GetNbinsX()
  
  def init(self, filename) :
    f = TFile(filename)
    keys = f.GetListOfKeys()
    for key in keys :
      if key.IsFolder() == False: continue
      hists = key.ReadObj().GetListOfKeys()
      for hist in hists :
        histogram = hist.ReadObj()
        histogram.SetDirectory(0) # <----- HERE
        self.pdfs[hist.GetName()] = histogram 

if __name__ == "__main__" :
  d = dummyClass("./pdfQG_AK4chs_13TeV.root")
  print "done"

Note the " histogram.SetDirectory(0)".
If you want, you can have a look to root.cern.ch/root/htmldoc/guides … Output.pdf , paragraph 1.2 for quite many details.

Cheers,
Danilo

ciao danilo

it works!

grazie mille
f