ROOT   Reference Guide
pyroot005_tfile_context_manager.py
Go to the documentation of this file.
1## \file
2## \ingroup tutorial_pyroot
3## \notebook -nodraw
4##
5## This tutorial demonstrates the usage of the TFile class as a Python context
6## manager.
7##
8## \macro_code
9## \macro_output
10##
11## \date March 2022
12## \author Vincenzo Eduardo Padulano CERN/UPV
13import os
14
15import ROOT
16from ROOT import TFile
17
18# By default, objects of some ROOT types such as TH1 and its derived types
19# are automatically attached to a ROOT.TDirectory when they are created.
20# Specifically, at any given point of a ROOT application, the ROOT.gDirectory
21# object tells which is the current directory where objects will be attached to.
22# The next line will print 'PyROOT' as the name of the current directory.
23# That is the global directory created when using ROOT from Python, which is
24# the ROOT.gROOT object.
25print("Current directory: '{}'.\n".format(ROOT.gDirectory.GetName()))
26
27# We can check to which directory a newly created histogram is attached.
28histo_1 = ROOT.TH1F("histo_1", "histo_1", 10, 0, 10)
29print("Histogram '{}' is attached to: '{}'.\n".format(histo_1.GetName(), histo_1.GetDirectory().GetName()))
30
31# For quick saving and forgetting of objects into ROOT files, it is possible to
32# open a TFile as a Python context manager. In the context, objects can be
33# created, modified and finally written to the file. At the end of the context,
34# the file will be automatically closed.
35with TFile.Open("pyroot005_file_1.root", "recreate") as f:
36 histo_2 = ROOT.TH1F("histo_2", "histo_2", 10, 0, 10)
37 # Inside the context, the current directory is the open file
38 print("Current directory: '{}'.\n".format(ROOT.gDirectory.GetName()))
39 # And the created histogram is automatically attached to the file
40 print("Histogram '{}' is attached to: '{}'.\n".format(histo_2.GetName(), histo_2.GetDirectory().GetName()))
41 # Before exiting the context, objects can be written to the file
42 f.WriteObject(histo_2, "my_histogram")
43
44# When the TFile.Close method is called, the current directory is automatically
45# set again to ROOT.gROOT. Objects that were attached to the file inside the
46# context are automatically deleted and made 'None' when the file is closed.
47print("Status after the first TFile context manager:")
48print(" Current directory: '{}'.".format(ROOT.gDirectory.GetName()))
49print(" Accessing 'histo_2' gives: '{}'.\n".format(histo_2))
50
51# Also reading data from a TFile can be done in a context manager. Information
52# stored in the objects of the file can be queried and used inside the context.
53# After the context, the objects are not usable anymore because the file is
54# automatically closed. This means you should use this pattern as a quick way
55# to get information or modify objects from a certain file, without needing to
56# keep the histograms alive afterwards.