Give TMultiGraph and THStack an __iter__ method

Hey, it would be cool if the two collections for graphs and histograms, TMultiGraph and THStack would naturally support iterating over them in Python.

All that is needed is basically:

ROOT.THStack.__iter__ = lambda self: iter(self.GetHists())
ROOT.TMultiGraph.__iter__ = lambda self: iter(self.GetListOfGraphs())

or, if done properly:

class ROOT.THStack(...):
    ...
    def __iter__(self):
        return iter(self.GetHists())

With this it becomes trivial to do, e.g.:

h1 = ROOT.TH1D("h1", "h1", 100, 0, 100)
h2 = ROOT.TH1D("h2", "h2", 100, 0, 100)
stack = ROOT.THStack()
stack.Add(h1)
stack.Add(h2)
for hist in stack:
    print hist.GetTitle()
1 Like

Hi,

Good idea! All we need is begin() and end() for these two classes. Would you mind sending in a pull request at https://github.com/root-mirror/root ?

If you don’t want to code it then we’ll do it - let me know!

Axel.

Hey,

I’m not exactly sure how to proceed on that one. Do I need to find the explicit python binding of THStack or would I need to implement it in the C++ class so it would automatically be picked up?

Andreas

Also, for Python’s full iterator interface you need to implement the __iter__ method and the next (or __next__ for Pyhton3) method?

Hi - sorry, I was too terse. Here’s the deal: once the C++ classes have begin() and end(), PyROOT will recognize them as iterable and map what’s needed to the python world.

I.e. all that’s missing is begin() and end() methods for the C++ classes.

Cheers, Axel.

Hey Axel,
have a look at the PR: https://github.com/root-mirror/root/pull/371

1 Like