Initializing a TBranch in PyROOT with a custom class in Python

Hello everyone,

I have a question about how I can make a custom class written in Python known to ROOT so that I can store an object of that class in a ROOT TBranch.

My custom Python class is a simple class that looks like this:

class Event:
    def __init___(self):
        self.event_data = {} # Python dictionary with 36-64 keys
        self.event_num = 0 # Int
    def load_data (self, event_num, data):
        self.event_data = data
        self.event_num = event_num

I then try to load this event into a TBranch as below

with ROOT.TFile("test_tree.root", "RECREATE") as infile:
    tree = ROOT.TTree("Event_Tree", "Event_Tree")
    for times in range(0, 5):
        dummy_event = Event()
        dummy_event.load_data(1, {1: [1, 2, 3], 2:[5, 6, 7]})
        branch_name = "Event_obj"
        tree.Branch(branch_name, dummy_event)
        tree.Fill()
        tree.Write()
    print("Done!")

However, running this code gives me the error “TypeError: Template method resolution failed:
none of the 8 overloaded methods succeeded.” I realize that my custom class “isn’t known to ROOT” as it says on the ROOT CERN TTree documentation page.

How do I make my class known to ROOT so that I can put objects of the Event class in branches of my TTree? For context, I am relatively new to C++ so I would appreciate some pointers here if there is some C++ required!

Thanks!

_ROOT Version: 6.32.02
_Platform: Ubuntu 22.04.5 LTS
_Compiler: linux8664gcc

Hello @RobinS,

welcome to the ROOT Forum! You have first to generate the dictionary for your class and then you can use it from Python too. See this example for a vector of vectors structure.

Cheers,
Monica

What does generating a dictionary for my class mean in this context? Do you mean that I have to write a C++ file redefining my Python class and use an std::map<int, std::vector>?

If so, when I’m reading my stored events back from my tree, how would I do this? Do I simply create an object of my class first and then read into it like so?

temp_event = Event()
tree.SetBranchAddress("event1", Event)

Will ROOT understand how to link the stored data back into my object structure?

Do you mean that I have to write a C++ file redefining my Python class

If you need store a class in a TTree, you will indeed need a C++ (interpreted via Cling and gInterpreter or compiled via the generation of a dictionary).

However you might need to store class and you might be able to just store the individual component of your Event each in their own branch.

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