Skip to content

Commit 7b7ec00

Browse files
committed
[ROOT] Use value_type instead of string manipulation to pythonize stl vector
1 parent 3b744f5 commit 7b7ec00

1 file changed

Lines changed: 33 additions & 3 deletions

File tree

  • bindings/pyroot/pythonizations/python/ROOT/_pythonization

bindings/pyroot/pythonizations/python/ROOT/_pythonization/_stl_vector.py

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,10 @@
88
# For the list of contributors see $ROOTSYS/README/CREDITS. #
99
################################################################################
1010

11+
import sys
12+
1113
from . import pythonization
12-
from ._rvec import add_array_interface_property
14+
from ._rvec import _array_interface_dtype_map
1315

1416

1517
def _data_vec_char(self):
@@ -24,15 +26,43 @@ def _data_vec_char(self):
2426
self.pop_back()
2527
return d
2628

29+
30+
def _get_array_interface(self):
31+
import ROOT
32+
33+
value_type = getattr(type(self), "value_type", None)
34+
dtype_numpy = _array_interface_dtype_map.get(value_type)
35+
if dtype_numpy is not None:
36+
dtype_size = ROOT._cppyy.sizeof(value_type)
37+
endianness = "<" if sys.byteorder == "little" else ">"
38+
size = self.size()
39+
# Numpy breaks for data pointer of 0 even though the array is empty.
40+
# We set the pointer to 1 but the value itself is arbitrary and never accessed.
41+
if self.empty():
42+
pointer = 1
43+
else:
44+
pointer = ROOT._cppyy.ll.addressof(self.data())
45+
return {
46+
"shape": (size,),
47+
"typestr": "{}{}{}".format(endianness, dtype_numpy, dtype_size),
48+
"version": 3,
49+
"data": (pointer, False),
50+
}
51+
52+
53+
def _add_array_interface_property(klass):
54+
value_type = getattr(klass, "value_type", None)
55+
if value_type in _array_interface_dtype_map:
56+
klass.__array_interface__ = property(_get_array_interface)
57+
2758
@pythonization("vector<", ns="std", is_prefix=True)
2859
def pythonize_stl_vector(klass, name):
2960
# Parameters:
3061
# klass: class to be pythonized
3162
# name: string containing the name of the class
3263

3364
# Add numpy array interface
34-
# NOTE: The pythonization is reused from ROOT::VecOps::RVec
35-
add_array_interface_property(klass, name)
65+
_add_array_interface_property(klass)
3666

3767
# Inject custom vector<char>::data()
3868
value_type = getattr(klass, 'value_type', None)

0 commit comments

Comments
 (0)