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:

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

$ python
Traceback (most recent call last):
File “”, line 36, in
d = dummyClass(“pdfQG_AK4chs_13TeV.root”)
File “”, 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?

f (719 Bytes) (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 = {}
    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 … Output.pdf , paragraph 1.2 for quite many details.


ciao danilo

it works!

grazie mille