-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy path_rfile.py
More file actions
182 lines (142 loc) · 5.73 KB
/
Copy path_rfile.py
File metadata and controls
182 lines (142 loc) · 5.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# Author: Giacomo Parolini CERN 04/2025
r"""
\pythondoc RFile
TODO: document RFile
\code{.py}
# TODO code example
\endcode
\endpythondoc
"""
from . import pythonization
class _RFile_Get:
"""
Allow access to objects through the method Get().
This is pythonized to allow Get() to be called both with and without a template argument.
"""
def __init__(self, rfile):
self._rfile = rfile
def __call__(self, namecycle):
"""
Non-templated Get()
"""
import ROOT
key = self._rfile.GetKeyInfo(namecycle)
if key:
obj = ROOT.Experimental.Internal.RFile_GetObjectFromKey(self._rfile, key)
return ROOT._cppyy.bind_object(obj, key.GetClassName())
# No key
return None
def __getitem__(self, template_arg):
"""
Templated Get()
"""
def getitem_wrapper(namecycle):
obj = self._rfile._OriginalGet[template_arg](namecycle)
return obj if obj else None
return getitem_wrapper
class _RFile_Put:
"""
Allow writing objects through the method Put().
This is pythonized to allow Put() to be called both with and without a template argument.
"""
def __init__(self, rfile):
self._rfile = rfile
def __call__(self, name, obj, title = ""):
"""
Non-templated Put()
"""
objType = type(obj)
if isinstance(obj, str):
# special case: automatically convert python str to std::string
className = "std::string"
elif not hasattr(objType, "__cpp_name__"):
raise TypeError(f"type {objType} is not supported by ROOT I/O")
else:
className = objType.__cpp_name__
self._rfile.Put[className](name, obj, title)
def __getitem__(self, template_arg):
"""
Templated Put()
"""
return self._rfile._OriginalPut[template_arg]
def _RFileExit(obj, exc_type, exc_val, exc_tb):
"""
Close the RFile object.
Signature and return value are imposed by Python, see
https://docs.python.org/3/library/stdtypes.html#typecontextmanager.
"""
obj.Close()
return False
def _RFileOpen(original):
"""
Pythonization for the factory methods (Recreate, Open, Update)
"""
def rfile_open_wrapper(klass, *args):
rfile = original(*args)
rfile._OriginalGet = rfile.Get
rfile.Get = _RFile_Get(rfile)
rfile._OriginalPut = rfile.Put
rfile.Put = _RFile_Put(rfile)
return rfile
return rfile_open_wrapper
def _RFileInit(rfile):
"""
Prevent the creation of RFile through constructor (must use a factory method)
"""
raise NotImplementedError("RFile can only be created via Recreate, Open or Update")
def _GetKeyInfo(rfile, path):
key = rfile._OriginalGetKeyInfo(path)
if key.has_value():
return key.value()
return None
def _ListKeys(rfile, basePath="", **kwargs):
"""
Returns an iterable over all keys of objects and/or directories written into this RFile starting at path
`basePath` (defaulting to include the content of all subdirectories).
By default, keys referring to directories are not returned: only those referring to leaf objects are.
If `basePath` is the path of a leaf object, only `basePath` itself will be returned.
If it is the path of a directory, it will not be included in the listing.
You can specify what to list via the keyword arguments:
- if `listObjects == True`, the listing will include keys of non-directory objects (default);
- if `listDirs == True`, the listing will include keys of directory objects;
- if `listRecursive == True`, the listing will recurse on all subdirectories of `basePath` (default),
otherwise it will only list immediate children of `basePath`.
Example usage:
~~~{.py}
for key in file.ListKeys():
# iterate over all objects in the RFile
print(f"{key.GetPath()};{key.GetCycle()} of type {key.GetClassName()}")
for key in file.ListKeys("", listDirs=True):
# iterate over all objects and directories in the RFile
print(f"{key.GetPath()};{key.GetCycle()} of type {key.GetClassName()}")
for key in file.ListKeys("a/b", listRecursive=False):
# iterate over all objects that are immediate children of directory "a/b"
print(f"{key.GetPath()};{key.GetCycle()} of type {key.GetClassName()}")
for key in file.ListKeys("foo", listDirs=True, listObjects=False):
# iterate over all directories under directory "foo", recursively
print(key.GetPath())
~~~
"""
from ROOT.Experimental import RFile
listObjects = kwargs['listObjects'] if 'listObjects' in kwargs else True
listDirs = kwargs['listDirs'] if 'listDirs' in kwargs else False
listRecursive = kwargs['listRecursive'] if 'listRecursive' in kwargs else True
flags = (listObjects * RFile.kListObjects) | (listDirs * RFile.kListDirs) | (listRecursive * RFile.kListRecursive)
iter = rfile._OriginalListKeys(basePath, flags)
return iter
@pythonization("RFile", ns="ROOT::Experimental")
def pythonize_rfile(klass):
# Explicitly prevent to create a RFile via ctor
klass.__init__ = _RFileInit
# Pythonize factory methods
klass.Open = classmethod(_RFileOpen(klass.Open))
klass.Update = classmethod(_RFileOpen(klass.Update))
klass.Recreate = classmethod(_RFileOpen(klass.Recreate))
# Pythonization for __enter__ and __exit__ methods
# These make RFile usable in a `with` statement as a context manager
klass.__enter__ = lambda rfile: rfile
klass.__exit__ = _RFileExit
klass._OriginalGetKeyInfo = klass.GetKeyInfo
klass.GetKeyInfo = _GetKeyInfo
klass._OriginalListKeys = klass.ListKeys
klass.ListKeys = _ListKeys