Logo ROOT   6.30.04
Reference Guide
 All Namespaces Files Pages
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 
15 import ROOT
16 
17 # Create an object with PyROOT
18 obj = ROOT.std.vector("int")(3)
19 for 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.
24 print(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`.
28 print(str(obj))
29 print("{}".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.
34 print(repr(obj))
35 obj
36 
37 # The print output behaves similar to the ROOT prompt, e.g., here for a ROOT histogram.
38 hist = ROOT.TH1F("name", "title", 10, 0, 1)
39 print(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
43 ROOT.gInterpreter.Declare('class MyClass {};')
44 m = ROOT.MyClass()
45 print(m)
46 print(str(m) == repr(m))
47