Check for branch existence in a TChain

I’m looping over a bunch of entries in a collection of files by adding them to a TChain object. The problem is the TTree object in each file doesn’t always have all of the same branches. Of course, when I call up an entry (using GetEntry), pyROOT throws an AttributeError when I try to do something with a branch that does not exist in that entry. The Draw command works just fine, but I’m trying to do an analysis where I am stepping back and forth over some events (checking for correlations to the previous or next event). The easiest solution is to simply bring up an entry in the TChain, check for the existence of the branch I’m after, and then do my analysis if that branch is there. I’m having a hard time figuring out how to do that existence check though. Does anyone have a suggestion?

Cheers,

Vic

Vic,

arguably, the AttributeError is a proper existence check, as it can be caught and handled. Alternatively, you can use hasattr(tree, ‘branch_name’).

HTH,
Wim

It turns out that both TTree and TChain have a function called “GetListOfBranches()” that returns pretty much exactly what you think they should (a list of branches in the TTree/TChain). You can simply loop over the elements in that list to pick up the one you want. Concretely, it looks something like:

for branch in Chain.GetListOfBranches():
  if( branch.GetName() == "TheBranchIWant" ):
    DoSomeAnalysis()

This side steps the AttributeError nicely. Once I figured out that this function existed, it did exactly what I want in a way that is both intuitive and fast.

Vic