{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# pyroot005_tfile_context_manager\n",
    "\n",
    "This tutorial demonstrates the usage of the TFile class as a Python context\n",
    "manager.\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "**Author:** Vincenzo Eduardo Padulano CERN/UPV  \n",
    "<i><small>This notebook tutorial was automatically generated with <a href= \"https://github.com/root-project/root/blob/master/documentation/doxygen/converttonotebook.py\">ROOTBOOK-izer</a> from the macro found in the ROOT repository  on Tuesday, August 09, 2022 at 09:38 AM.</small></i>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Welcome to JupyROOT 6.27/01\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "\n",
    "import ROOT\n",
    "from ROOT import TFile"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "By default, objects of some ROOT types such as `TH1` and its derived types\n",
    "are automatically attached to a ROOT.TDirectory when they are created.\n",
    "Specifically, at any given point of a ROOT application, the ROOT.gDirectory\n",
    "object tells which is the current directory where objects will be attached to.\n",
    "The next line will print 'PyROOT' as the name of the current directory.\n",
    "That is the global directory created when using ROOT from Python, which is\n",
    "the ROOT.gROOT object."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Current directory: 'PyROOT'.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print(\"Current directory: '{}'.\\n\".format(ROOT.gDirectory.GetName()))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can check to which directory a newly created histogram is attached."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Histogram 'histo_1' is attached to: 'PyROOT'.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "histo_1 = ROOT.TH1F(\"histo_1\", \"histo_1\", 10, 0, 10)\n",
    "print(\"Histogram '{}' is attached to: '{}'.\\n\".format(histo_1.GetName(), histo_1.GetDirectory().GetName()))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For quick saving and forgetting of objects into ROOT files, it is possible to\n",
    "open a TFile as a Python context manager. In the context, objects can be\n",
    "created, modified and finally written to the file. At the end of the context,\n",
    "the file will be automatically closed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Current directory: 'pyroot005_file_1.root'.\n",
      "\n",
      "Histogram 'histo_2' is attached to: 'pyroot005_file_1.root'.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "with TFile.Open(\"pyroot005_file_1.root\", \"recreate\") as f:\n",
    "    histo_2 = ROOT.TH1F(\"histo_2\", \"histo_2\", 10, 0, 10)\n",
    "    # Inside the context, the current directory is the open file\n",
    "    print(\"Current directory: '{}'.\\n\".format(ROOT.gDirectory.GetName()))\n",
    "    # And the created histogram is automatically attached to the file\n",
    "    print(\"Histogram '{}' is attached to: '{}'.\\n\".format(histo_2.GetName(), histo_2.GetDirectory().GetName()))\n",
    "    # Before exiting the context, objects can be written to the file\n",
    "    f.WriteObject(histo_2, \"my_histogram\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When the TFile.Close method is called, the current directory is automatically\n",
    "set again to ROOT.gROOT. Objects that were attached to the file inside the\n",
    "context are automatically deleted and made 'None' when the file is closed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Status after the first TFile context manager:\n",
      " Current directory: 'PyROOT'.\n",
      " Accessing 'histo_2' gives: 'None'.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print(\"Status after the first TFile context manager:\")\n",
    "print(\" Current directory: '{}'.\".format(ROOT.gDirectory.GetName()))\n",
    "print(\" Accessing 'histo_2' gives: '{}'.\\n\".format(histo_2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Also reading data from a TFile can be done in a context manager. Information\n",
    "stored in the objects of the file can be queried and used inside the context.\n",
    "After the context, the objects are not usable anymore because the file is\n",
    "automatically closed. This means you should use this pattern as a quick way\n",
    "to get information or modify objects from a certain file, without needing to\n",
    "keep the histograms alive afterwards."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Retrieved 'histo_2' histogram from file 'pyroot005_file_1.root'.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "with TFile.Open(\"pyroot005_file_1.root\", \"read\") as f:\n",
    "    # Retrieve histogram using the name given to f.WriteObject in the previous\n",
    "    # with statement\n",
    "    histo_2_fromfile = f.my_histogram\n",
    "    print(\"Retrieved '{}' histogram from file '{}'.\\n\".format(histo_2_fromfile.GetName(), f.GetName()))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Cleanup the file created for this tutorial"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "os.remove(\"pyroot005_file_1.root\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
