The Python extension module PyROOT provides the bindings to the ROOT class library in a generic way using the CINT dictionary: the user may use all ROOT classes from the Python interpreter. In addition, PyROOT may be loaded into the CINT interpreter to access Python classes via the TPython class.
Before a ROOT class can be used from Python, its dictionary needs to be loaded into the current process. This happens automatically for all classes in the ROOT distribution, whereas user-defined classes need first to be loaded in ROOT, for example via ACLiC, before being imported in Python. Here is an example of usage of ROOT and STL classes from inside a Python program:from ROOT import TCanvas # available at startup c = TCanvas() from ROOT import TLorentzVector # triggers auto-load of libPhysics l = TLorentzVector() from ROOT import std v = std.vector(int)() for i in range(0,10): v.push_back(i)
Most globals and global functions are available since the beginning, and the behavior of ROOT globals is the same as python globals: they can be changed only through their containing module. Several examples are provided in the $ROOTSYS/tutorials/pyroot directory.
from ROOT import * # global import, easy but NOT recommended print gDebug # prints 0 gROOT.ProcessLine( 'gDebug = 7;' ) print gDebug # prints 0 again gDebug = 5 # changed the local reference print gDebug # now prints 5 gROOT.ProcessLine( 'cout << gDebug << endl;' ) # prints 7 import ROOT # this is a much better way to access ROOT! print ROOT.gDebug # prints 7 ROOT.gDebug = 3 gROOT.ProcessLine( 'cout << gDebug << endl;' ) # prints 3
The performance of a Python script is similar to that of a CINT macro. Differences occur mainly because of differences in the respective languages: C++ is much harder to parse but, once parsed, it is much easier to optimize. Consequently, individual calls to ROOT are typically faster from PyROOT, whereas loops are typically slower. The usual approach of Python developers is to convert the critical parts into compiled C++ code to be loaded as an extension module. The best habit is to spend most of the time in compiled code, making maximum use of ROOT facilities.