Logo ROOT  
Reference Guide
pyroot003_prettyPrinting.py
Go to the documentation of this file.
1## \file
2## \ingroup tutorial_pyroot
3## \notebook -nodraw
4## This tutorial illustrates the pretty printing feature of PyROOT, which reveals
5## the content of the object if a string representation is requested, e.g., by
6## Python's print statement. The printing behaves similar to the ROOT prompt
7## powered by the C++ interpreter cling.
8##
9## \macro_code
10## \macro_output
11##
12## \date June 2018
13## \author Stefan Wunsch, Enric Tejedor
14
15import ROOT
16
17# Create an object with PyROOT
18obj = ROOT.std.vector("int")(3)
19for i in range(obj.size()):
20 obj[i] = i
21
22# Print the object, which reveals the content. Note that `print` calls the special
23# method `__str__` of the object internally.
24print(obj)
25
26# The output can be retrieved as string by any function that triggers the `__str__`
27# special method of the object, e.g., `str` or `format`.
28print(str(obj))
29print("{}".format(obj))
30
31# Note that the interactive Python prompt does not call `__str__`, it calls
32# `__repr__`, which implements a formal and unique string representation of
33# the object.
34print(repr(obj))
35obj
36
37# The print output behaves similar to the ROOT prompt, e.g., here for a ROOT histogram.
38hist = ROOT.TH1F("name", "title", 10, 0, 1)
39print(hist)
40
41# If cling cannot produce any nice representation for the class, we fall back to a
42# "<ClassName at address>" format, which is what `__repr__` returns
43ROOT.gInterpreter.Declare('class MyClass {};')
44m = ROOT.MyClass()
45print(m)
46print(str(m) == repr(m))
47