Get a Variable from RooAbsPdf in PyROOT

I see, yes Python takes ownership of everything.

In that case, you can release the Python ownership and pass it to the RooFit pdf, then you don’t need to do the bookkeeping yourself:

import ROOT

def release_python_ownership(args):
    for arg in args:
        ROOT.SetOwnership(arg, False)
    return args

def create_pdf():

    x = ROOT.RooRealVar("x", "x", 0., -10., +10.)
    mu = ROOT.RooRealVar("mu", "mu", 0., -10., +10.)
    sigma = ROOT.RooRealVar("sigma", "sigma", 4., 0.01, 10.)

    gauss = ROOT.RooGaussian("gauss", "gauss", x, mu, sigma)

    variables = [x, mu, sigma]

    gauss.addOwnedComponents(release_python_ownership(variables))

    return gauss

gauss = create_pdf()

variables = gauss.getVariables()

variables[0].Print()
print(type(variables[0]))
print(variables[0].getVal())

Or using the RooWorkspace is also a good option, because then it owns all the RooFit objects (in fact this is what most RooFit-based frameworks do).

1 Like