NoneType Feturned from Function that returns TH1F

Hi All,

I am trying to write a function that opens a file, gets a histogram and returns that histogram. But when I implement the function, it seems to return “PyROOT_NoneType” and so I cannot use the returned histogram outside of the function. I cannot figure out why this may be the case because when I write a very similar function but which creates a histogram within it, instead of reading it from a file, it works fine.

I paste below my test code I am using to figure this out. It should be standalone and create a dummy TFile that contains a simple histogram that is then intended to be grabbed back from this function.

Any help is much appreciated.

Thanks,
Sam

###########################

from ROOT import *

THIS FUNCTION WORKS

def ProduceHist(name):
h = TH1F(name,name,20,0,20)
print "Type in function of hist h: ",type(h)
sh = h
print "Type in function of hist sh: ",type(sh)
return sh

myh2 = ProduceHist(“mhh2”)
print “Type of hist returned from function:”,type(myh2)
myh2.Draw(“hist”)

THIS FUNCTION DOESNT WORK

def GetHistFromFile(file, histname):
ftemp = TFile(file)
print "Type in function of file: ",type(ftemp)
sh = ftemp.Get(“htemp”)
print "In function of hist: ",type(sh)
return sh

htemp = TH1F(“htemp”,“htemp”,10,0,10)
htemp.Fill(5)

f=TFile(“fdel.root”,“RECREATE”)
htemp.Write(“htemp”)
f.Close()

myh = GetHistFromFile(“fdel.root”,“htemp”)
print “Type of hist returned from function:”,type(myh)
myh.Draw(“hist”)

###########################

sh = ftemp.Get(“htemp”)
sh.SetDirectory(gROOT) # (gROOT) or (0) # detach “sh” from the “ftemp” file

1 Like

Hi Wile,

Thank you very much! This worked.

Sam