Skip to content
Snippets Groups Projects
Commit 0778c11a authored by Enric Tejedor Saavedra's avatar Enric Tejedor Saavedra
Browse files

[Exp PyROOT] TVectorT: add __getitem__ pythonisation with checked bounds

Throws IndexError if index is out of bounds and also makes it possible
to iterate over a TVectorT.
parent c257a7aa
No related branches found
No related tags found
No related merge requests found
# Author: Stefan Wunsch CERN 06/2018 # Author: Stefan Wunsch, Enric Tejedor CERN 06/2018
################################################################################ ################################################################################
# Copyright (C) 1995-2018, Rene Brun and Fons Rademakers. # # Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. #
# All rights reserved. # # All rights reserved. #
# # # #
# For the licensing terms see $ROOTSYS/LICENSE. # # For the licensing terms see $ROOTSYS/LICENSE. #
...@@ -11,6 +11,28 @@ ...@@ -11,6 +11,28 @@
from libROOTPython import AddPrettyPrintingPyz from libROOTPython import AddPrettyPrintingPyz
from ROOT import pythonization from ROOT import pythonization
def _add_getitem_checked(klass):
# Parameters:
# - klass: class where to add a __getitem__ method that raises
# IndexError if index is out of range
def getitem_checked(o, i):
# Get item of `o` at `i` or raise IndexError if index is
# out of range.
# Assumes `o` has `__len__`.
# Parameters:
# - o: object
# - i: index to be checked in object
# Returns:
# - o[i]
if i >= 0 and i < len(o):
return o._getitem__unchecked(i)
else:
raise IndexError('index out of range')
klass._getitem__unchecked = klass.__getitem__
klass.__getitem__ = getitem_checked
@pythonization() @pythonization()
def pythonizegeneric(klass, name): def pythonizegeneric(klass, name):
......
...@@ -10,6 +10,8 @@ ...@@ -10,6 +10,8 @@
from ROOT import pythonization from ROOT import pythonization
from ._generic import _add_getitem_checked
@pythonization() @pythonization()
def pythonize_tvectort(klass, name): def pythonize_tvectort(klass, name):
...@@ -21,4 +23,9 @@ def pythonize_tvectort(klass, name): ...@@ -21,4 +23,9 @@ def pythonize_tvectort(klass, name):
# Support `len(v)` as `v.GetNoElements()` # Support `len(v)` as `v.GetNoElements()`
klass.__len__ = klass.GetNoElements klass.__len__ = klass.GetNoElements
# Add checked __getitem__.
# Allows to throw pythonic IndexError when index is out of range
# and to iterate over the vector.
_add_getitem_checked(klass)
return True return True
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment