Skip to content

Commit c2ee872

Browse files
committed
[Python] Explicitly drop ownership of arguments to TH2Poly::AddBin()
This follows up on 7ac08ad, ensuring the object ownership is also handled correctly in `TH2Poly::AddBin()`. This is motivated by usage of `TH2Poly` in CMSSW unit tests, and a ROOT unit test that covers the same usage pattern is now added as well.
1 parent 2a74548 commit c2ee872

2 files changed

Lines changed: 54 additions & 0 deletions

File tree

  • bindings/pyroot/pythonizations

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

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,17 @@ def _FillWithArrayTH2(self, *args):
6060
return self.FillN(n, x, y, weights)
6161

6262

63+
def _TH2Poly_AddBin(self, *args, **kwargs):
64+
"""
65+
The TH2Poly always takes ownership of the added bin objects.
66+
"""
67+
from ROOT._pythonization._memory_utils import declare_cpp_owned_arg
68+
69+
declare_cpp_owned_arg(0, "poly", args, kwargs)
70+
71+
self._AddBin(*args, **kwargs)
72+
73+
6374
# The constructors need to be pythonized for each derived class separately:
6475
_th2_derived_classes_to_pythonize = [
6576
"TH2C",
@@ -89,3 +100,9 @@ def _FillWithArrayTH2(self, *args):
89100
def _enable_numpy_fill(klass):
90101
klass._Fill = klass.Fill
91102
klass.Fill = _FillWithArrayTH2
103+
104+
105+
@pythonization("TH2Poly")
106+
def _pythonize_th2poly(klass):
107+
klass._AddBin = klass.AddBin
108+
klass.AddBin = _TH2Poly_AddBin

bindings/pyroot/pythonizations/test/th2.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,5 +54,42 @@ def test_scalar_multiplication_right(self):
5454
self.assertAlmostEqual(hscaled.GetBinContent(1, 1), 4.0)
5555

5656

57+
class TH2Poly(unittest.TestCase):
58+
"""
59+
Test TH2Poly.
60+
"""
61+
62+
def test_add_bin_ownership(self):
63+
"""Verify that Python releases the ownership of the objects passed to TH2Poly::AddBin()"""
64+
h2p = ROOT.TH2Poly()
65+
66+
def add_bins():
67+
68+
n = 4
69+
70+
g1 = ROOT.TGraph(n)
71+
for i, x, y in zip(range(n), [0.0, 1.0, 1.0, 0.0], [0.0, 0.0, 1.0, 1.0]):
72+
g1.SetPoint(i, x, y)
73+
74+
g2 = ROOT.TGraph(n)
75+
for i, x, y in zip(range(n), [1.0, 2.0, 2.0, 1.0], [0.0, 0.0, 1.0, 1.0]):
76+
g2.SetPoint(i, x, y)
77+
78+
g3 = ROOT.TGraph(n)
79+
for i, x, y in zip(range(n), [0.0, 1.0, 1.0, 0.0], [1.0, 1.0, 2.0, 2.0]):
80+
g3.SetPoint(i, x, y)
81+
82+
h2p.AddBin(g1)
83+
h2p.AddBin(g2)
84+
h2p.AddBin(g3)
85+
86+
add_bins()
87+
88+
# Fill some values
89+
h2p.Fill(0.5, 0.5, 2)
90+
h2p.Fill(1.5, 0.5, 5)
91+
h2p.Fill(0.5, 1.5, 3)
92+
93+
5794
if __name__ == "__main__":
5895
unittest.main()

0 commit comments

Comments
 (0)