Logo ROOT   6.16/01
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##
11## \date June 2018
12## \author Stefan Wunsch, Enric Tejedor
13
14import ROOT
15
16# Create an object with PyROOT
17obj = ROOT.std.vector("int")(3)
18for i in range(obj.size()):
19 obj[i] = i
20
21# Print the object, which reveals the content. Note that `print` calls the special
22# method `__str__` of the object internally.
23print(obj)
24
25# The output can be retrieved as string by any function that triggers the `__str__`
26# special method of the object, e.g., `str` or `format`.
27print(str(obj))
28print("{}".format(obj))
29
30# Note that the interactive Python prompt does not call `__str__`, it calls
31# `__repr__`, which implements a formal and unique string representation of
32# the object.
33print(repr(obj))
34obj
35
36# The print output behaves similar to the ROOT prompt, e.g., here for a ROOT histogram.
37hist = ROOT.TH1F("name", "title", 10, 0, 1)
38print(hist)
39
40# If cling cannot produce any nice representation for the class, we fall back to a
41# "<ClassName at address>" format, which is what `__repr__` returns
42ROOT.gInterpreter.Declare('class MyClass {};')
43m = ROOT.MyClass()
44print(m)
45print(str(m) == repr(m))
46