{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "e4d28579",
   "metadata": {},
   "source": [
    "# tcontext_context_manager\n",
    "This tutorial demonstrates the usage of the TContext class as a Python context\n",
    "manager. This functionality is related with how TFile works, so it is\n",
    "suggested to also take a look at the tfile_context_manager.py tutorial.\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, May 19, 2026 at 08:16 PM.</small></i>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "bdabbb89",
   "metadata": {
    "collapsed": false,
    "execution": {
     "iopub.execute_input": "2026-05-19T20:16:41.009839Z",
     "iopub.status.busy": "2026-05-19T20:16:41.009724Z",
     "iopub.status.idle": "2026-05-19T20:16:41.965041Z",
     "shell.execute_reply": "2026-05-19T20:16:41.964616Z"
    }
   },
   "outputs": [],
   "source": [
    "import os\n",
    "import sys\n",
    "\n",
    "import ROOT\n",
    "from ROOT import TDirectory, TFile, gROOT"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8c593f86",
   "metadata": {},
   "source": [
    "Sometimes it is useful to have multiple open files at once. In such cases,\n",
    "the current directory will always be the file that was open last."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "d789ccee",
   "metadata": {
    "collapsed": false,
    "execution": {
     "iopub.execute_input": "2026-05-19T20:16:41.978422Z",
     "iopub.status.busy": "2026-05-19T20:16:41.978274Z",
     "iopub.status.idle": "2026-05-19T20:16:42.116615Z",
     "shell.execute_reply": "2026-05-19T20:16:42.115871Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Current directory: '/github/home/ROOT-CI/build/tutorials/io/tcontext_2.root'.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "path = str(gROOT.GetTutorialDir()) + '/io/'\n",
    "file_1 = TFile(path+\"tcontext_1.root\", \"recreate\")\n",
    "file_2 = TFile(path+\"tcontext_2.root\", \"recreate\")\n",
    "print(\"Current directory: '{}'.\\n\".format(ROOT.gDirectory.GetName()))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "310a32a8",
   "metadata": {},
   "source": [
    "Changing directory into another file can be safely done through a TContext\n",
    "context manager."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "ef3333ff",
   "metadata": {
    "collapsed": false,
    "execution": {
     "iopub.execute_input": "2026-05-19T20:16:42.118181Z",
     "iopub.status.busy": "2026-05-19T20:16:42.118056Z",
     "iopub.status.idle": "2026-05-19T20:16:42.260139Z",
     "shell.execute_reply": "2026-05-19T20:16:42.259362Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Current directory: '/github/home/ROOT-CI/build/tutorials/io/tcontext_1.root'.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "with TDirectory.TContext(file_1):\n",
    "    # Inside the statement, the current directory is file_1\n",
    "    print(\"Current directory: '{}'.\\n\".format(ROOT.gDirectory.GetName()))\n",
    "    histo_1 = ROOT.TH1F(\"histo_1\", \"histo_1\", 10, 0, 10)\n",
    "    file_1.WriteObject(histo_1, \"my_histogram\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e9759163",
   "metadata": {},
   "source": [
    "After the context, the current directory is restored back to file_2. Also, the\n",
    "two files are kept open. This means that objects read, written or modified\n",
    "inside the context are still available afterwards."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "af1ea353",
   "metadata": {
    "collapsed": false,
    "execution": {
     "iopub.execute_input": "2026-05-19T20:16:42.261938Z",
     "iopub.status.busy": "2026-05-19T20:16:42.261807Z",
     "iopub.status.idle": "2026-05-19T20:16:42.396913Z",
     "shell.execute_reply": "2026-05-19T20:16:42.378334Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Current directory: '/github/home/ROOT-CI/build/tutorials/io/tcontext_2.root'.\n",
      "\n",
      "'/github/home/ROOT-CI/build/tutorials/io/tcontext_1.root' and '/github/home/ROOT-CI/build/tutorials/io/tcontext_2.root' are open.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print(\"Current directory: '{}'.\\n\".format(ROOT.gDirectory.GetName()))\n",
    "if file_1.IsOpen() and file_2.IsOpen():\n",
    "    print(\"'{}' and '{}' are open.\\n\".format(file_1.GetName(), file_2.GetName()))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2a781275",
   "metadata": {},
   "source": [
    "TContext and TFile context managers can also be used in conjunction, allowing\n",
    "for safely:\n",
    "- Opening a file, creating, modifying, writing and reading objects in it.\n",
    "- Closing the file, storing it on disk.\n",
    "- Restoring the previous value of gDirectory to the latest file opened before\n",
    "  this context, rather than to the global ROOT.gROOT\n",
    "Remember that the TContext must be initialized before the TFile, otherwise the\n",
    "current directory would already be set to the file opened for this context."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "80590c8a",
   "metadata": {
    "collapsed": false,
    "execution": {
     "iopub.execute_input": "2026-05-19T20:16:42.398684Z",
     "iopub.status.busy": "2026-05-19T20:16:42.398530Z",
     "iopub.status.idle": "2026-05-19T20:16:42.521182Z",
     "shell.execute_reply": "2026-05-19T20:16:42.520638Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Current directory: '/github/home/ROOT-CI/build/tutorials/io/tcontext_3.root'.\n",
      "\n",
      "Current directory: '/github/home/ROOT-CI/build/tutorials/io/tcontext_2.root'.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "with TDirectory.TContext(), TFile(path+\"tcontext_3.root\", \"recreate\") as f:\n",
    "    print(\"Current directory: '{}'.\\n\".format(ROOT.gDirectory.GetName()))\n",
    "    histo_2 = ROOT.TH1F(\"histo_2\", \"histo_2\", 10, 0, 10)\n",
    "    f.WriteObject(histo_2, \"another_histogram\")\n",
    "\n",
    "print(\"Current directory: '{}'.\\n\".format(ROOT.gDirectory.GetName()))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d78ae5eb",
   "metadata": {},
   "source": [
    "Cleanup the files created for this tutorial"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "8c8fdcdf",
   "metadata": {
    "collapsed": false,
    "execution": {
     "iopub.execute_input": "2026-05-19T20:16:42.522903Z",
     "iopub.status.busy": "2026-05-19T20:16:42.522777Z",
     "iopub.status.idle": "2026-05-19T20:16:42.627704Z",
     "shell.execute_reply": "2026-05-19T20:16:42.627128Z"
    }
   },
   "outputs": [],
   "source": [
    "file_1.Close();\n",
    "file_2.Close();\n",
    "\n",
    "for i in range(1, 4):\n",
    "    os.remove(path+\"tcontext_{}.root\".format(i))"
   ]
  }
 ],
 "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.12.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
