Skip to content

Commit 696e591

Browse files
committed
Fix group by properties/callable Issue #1241
1 parent 2d8775e commit 696e591

File tree

2 files changed

+29
-3
lines changed

2 files changed

+29
-3
lines changed

src/build123d/topology/shape_core.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2983,10 +2983,17 @@ def key_f(obj):
29832983
return round(obj.volume, tol_digits)
29842984

29852985
elif callable(group_by):
2986-
key_f = group_by
2986+
raw_key_f = group_by
2987+
2988+
def key_f(obj):
2989+
val = raw_key_f(obj)
2990+
return round(val, tol_digits) if isinstance(val, (int, float)) else val
29872991

29882992
elif isinstance(group_by, property):
2989-
key_f = group_by.__get__
2993+
2994+
def key_f(obj):
2995+
val = group_by.__get__(obj)
2996+
return round(val, tol_digits) if isinstance(val, (int, float)) else val
29902997

29912998
else:
29922999
raise ValueError(f"Unsupported group_by function: {group_by}")

tests/test_direct_api/test_group_by.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,8 @@
3030
import unittest
3131

3232
from build123d.geometry import Axis
33-
from build123d.topology import Solid
33+
from build123d.topology import Edge, Solid
34+
from build123d.objects_curve import CenterArc
3435

3536

3637
class TestGroupBy(unittest.TestCase):
@@ -64,6 +65,24 @@ def test_pp(self):
6465
"[[Vertex(0.0, 0.0, 0.0), Vertex(0.0, 1.0, 0.0), Vertex(1.0, 0.0, 0.0), Vertex(1.0, 1.0, 0.0)], [Vertex(0.0, 0.0, 1.0), Vertex(0.0, 1.0, 1.0), Vertex(1.0, 0.0, 1.0), Vertex(1.0, 1.0, 1.0)]]",
6566
)
6667

68+
def test_properties(self):
69+
70+
c1 = CenterArc((-5, 0), 2, 0, 360)
71+
c2 = CenterArc((5, 0), 4, 0, 360)
72+
lines = Edge.make_constrained_lines(c1, c2)
73+
longest_lines = lines.group_by(Edge.length)[-1]
74+
self.assertEqual(len(longest_lines), 2)
75+
76+
def test_callable(self):
77+
def edge_length(e: Edge) -> float:
78+
return e.length
79+
80+
c1 = CenterArc((-5, 0), 2, 0, 360)
81+
c2 = CenterArc((5, 0), 4, 0, 360)
82+
lines = Edge.make_constrained_lines(c1, c2)
83+
longest_lines = lines.group_by(edge_length)[-1]
84+
self.assertEqual(len(longest_lines), 2)
85+
6786

6887
if __name__ == "__main__":
6988
unittest.main()

0 commit comments

Comments
 (0)