Home | News | Documentation | Download

Returning a histogram object

Hey guys,

I’d like to return a histogram object from one function to be used within another. I am returning the histogram, among other variables. Later, I use this histogram to make a RooDataHist. However, it seems that whatever is being returned loses its histogram type and therefore it is not a histogram anymore. For example

def plot_hist():
    file_name = "test"

    histogram = ROOT.TH1F(blah blah)
    return file_name, histogram

def otherFunc():
    file_name, histogram = plot_hist()
    rHist = ROOT.RooDataHist("" , "", , histogram)

Now this gives me an error where I initialise rHist because it needs a TH1F as the last parameter. but since I passed it between functions, the histogram lost its TH1F type. I tried getting the histogram via ROOT.gDirectory.Get(“histname”), but that still doesn’t hold its type. What can I do?


Hey Diyon,

I have tried to reproduce your problem, but I couldn’t.

More simple code akin to yours works for me:

def plot_hist():
    histogram = ROOT.TH1F("name", "title", 100, -1, 1)
    return histogram

def otherFunc():
    histogram = plot_hist()
    print(type(histogram)) # prints <class cppyy.gbl.TH1F at 0x54edb40>

I don’t have experience with RooDataHist, but from your code above code won’t work cause it misses 3rd argument, but that is not histogram issue.

So I assume something else cause TObject issue.

Maybe you can show code more detailed

I have tried with
root 6.22
python 3.7.6


Hi there!


Sry, I was wrong before. I cannot reproduce the error, my reproducer had a typo. Can you try to modify your reproducer so that it shows the issue?


Hey guys,

Thanks for replying, but I read somewhere that once I pass the histogram out of the scope of the function, it loses its type. I am not too sure of how ROOT and python work behind the scenes so I can’t comment there. Nevertheless, within that same post, I found a solution. An example would be:

def a_function():
    var1 = "test"
    var2 = 34
    histogram = ROOT.TH1F("hist","hist",200,1,5)
    histogram = ROOT.gDirectory.Get("hist")
    #This line is the important one

    return var1, var2, histogram

def another_function():

    var1, var2, histogram = a_function()
    #Do whatever with histogram now

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.