Pyroot 0 0 3_Pretty Printing

This tutorial illustrates the pretty printing feature of PyROOT, which reveals the content of the object if a string representation is requested, e.g., by Python's print statement. The printing behaves similar to the ROOT prompt powered by the C++ interpreter cling.

Author: Stefan Wunsch, Enric Tejedor
This notebook tutorial was automatically generated with ROOTBOOK-izer from the macro found in the ROOT repository on Thursday, June 04, 2020 at 02:47 AM.

In [1]:
import ROOT
Welcome to JupyROOT 6.23/01

Create an object with PyROOT

In [2]:
obj = ROOT.std.vector("int")(3)
for i in range(obj.size()):
    obj[i] = i

Print the object, which reveals the content. Note that print calls the special method __str__ of the object internally.

In [3]:
print(obj)
{ 0, 1, 2 }

The output can be retrieved as string by any function that triggers the __str__ special method of the object, e.g., str or format.

In [4]:
print(str(obj))
print("{}".format(obj))
{ 0, 1, 2 }
{ 0, 1, 2 }

Note that the interactive Python prompt does not call __str__, it calls __repr__, which implements a formal and unique string representation of the object.

In [5]:
print(repr(obj))
obj
<cppyy.gbl.std.vector<int> object at 0x5632c70c4ee0>
Out[5]:
<cppyy.gbl.std.vector<int> object at 0x5632c70c4ee0>

The print output behaves similar to the ROOT prompt, e.g., here for a ROOT histogram.

In [6]:
hist = ROOT.TH1F("name", "title", 10, 0, 1)
print(hist)
Name: name Title: title NbinsX: 10

If cling cannot produce any nice representation for the class, we fall back to a "" format, which is what __repr__ returns

In [7]:
ROOT.gInterpreter.Declare('class MyClass {};')
m = ROOT.MyClass()
print(m)
print(str(m) == repr(m))
<cppyy.gbl.MyClass object at 0x5632c73453a0>
True