Canvas primitives

Hi,

I want to pass a TCanvas object as the output of a python function and then manipulate the canvas.
However, the canvas primitives seem to be erased once I exit the function which created it.
How can I make sure the canvas primitives are being passed along with it?
Below is a simple example where this behavior appears:

from ROOT import (TGraph,TCanvas,Double,gROOT)

def getCanvas():
    canvas = TCanvas("Test Plot", "TEST", 0, 0, 800, 600)
    canvas.cd()
    grA = TGraph()
    grA.SetName("A")
    for i in range(10):
       grA.SetPoint(grA.GetN(),1.*i,2.*i)
    grA.Draw("AP")

    print 'len=',len(plane.GetListOfPrimitives())  #Here I get len=1
    for p in plane.GetListOfPrimitives():
        print p

    return canvas


if __name__ == "__main__":

    gROOT.SetBatch() 
    plane = getCanvas()
    print 'len=',len(plane.GetListOfPrimitives())  #Here I get len=0
    for p in plane.GetListOfPrimitives():
        print p 

I would expect both list of primitives to containg the “A” TGraph, but only the first print call (inside getCanvas) shows it. What am I doing wrong?

Hi,

nothing wrong.
The canvas does not own the primitives. The moment you return from your function, the graph is garbage collected and what you are left with is an empty canvas (rightfully, zero primitives as you point out).
You’ll have to make sure to avoid that these objects go out of scope. One of the many options is to bookkeep the list of primitives and return it together with the canvas, depending on the solution you are crafting.

Cheers,
D