Skip to content

Commit 9ac0001

Browse files
authored
Merge pull request #39 from petercorke/fix/edge-endpoints-read-only
fix: Edge.v1 and Edge.v2 are read-only
2 parents f3e1e04 + d8f7911 commit 9ac0001

2 files changed

Lines changed: 186 additions & 10 deletions

File tree

‎src/pgraph/PGraph.py‎

Lines changed: 65 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -642,8 +642,7 @@ def remove_edge(self, edge: Edge) -> None:
642642
v2._connectivitychange = True
643643
self._connectivitychange = True
644644

645-
edge.v1 = None
646-
edge.v2 = None
645+
edge._set_endpoints(None, None)
647646

648647
self._edgelist.remove(edge)
649648

@@ -2629,6 +2628,12 @@ def _graphcolor(self) -> int | None:
26292628
# ========================================================================== #
26302629

26312630

2631+
_ENDPOINT_MESSAGE = (
2632+
"Edge.{0} is read-only. Give the vertices to the constructor, Edge(v1, v2), "
2633+
"or connect the edge with v1.connect(v2, edge=e) or e.connect(v1, v2)"
2634+
)
2635+
2636+
26322637
class Edge:
26332638
"""
26342639
Edge class
@@ -2638,8 +2643,8 @@ class Edge:
26382643
Each edge has:
26392644
- ``cost`` cost of traversing this edge, required for planning methods
26402645
- ``data`` reference to arbitrary data associated with the edge
2641-
- ``v1`` first vertex, start vertex for a directed edge
2642-
- ``v2`` second vertex, end vertex for a directed edge
2646+
- ``v1`` first vertex, start vertex for a directed edge (read-only)
2647+
- ``v2`` second vertex, end vertex for a directed edge (read-only)
26432648
26442649
.. note::
26452650
@@ -2696,8 +2701,8 @@ def __init__(
26962701
26972702
:seealso: :meth:`Edge.connect` :meth:`BaseVertex.connect`
26982703
"""
2699-
self.v1 = v1
2700-
self.v2 = v2
2704+
self._v1 = v1
2705+
self._v2 = v2
27012706

27022707
self.data = data
27032708

@@ -2717,6 +2722,58 @@ def __init__(
27172722
else:
27182723
self.cost = None
27192724

2725+
@property
2726+
def v1(self) -> BaseVertex | None:
2727+
"""
2728+
First vertex of the edge, the start vertex for a directed edge
2729+
2730+
:return: the vertex, or None if the edge is not connected
2731+
:rtype: BaseVertex subclass or None
2732+
2733+
.. versionchanged:: 1.0
2734+
Read-only. It was a plain attribute, so assigning to it on an edge
2735+
that was in a graph left the graph inconsistent: the vertices'
2736+
edge lists no longer agreed with the edge, and the edge could not
2737+
be removed. Give the vertices to the constructor, ``Edge(v1,
2738+
v2)``, or to :meth:`connect` or :meth:`BaseVertex.connect`.
2739+
2740+
:seealso: :attr:`v2` :meth:`connect`
2741+
"""
2742+
return self._v1
2743+
2744+
@v1.setter
2745+
def v1(self, value: BaseVertex | None) -> None:
2746+
raise AttributeError(_ENDPOINT_MESSAGE.format("v1"))
2747+
2748+
@property
2749+
def v2(self) -> BaseVertex | None:
2750+
"""
2751+
Second vertex of the edge, the end vertex for a directed edge
2752+
2753+
:return: the vertex, or None if the edge is not connected
2754+
:rtype: BaseVertex subclass or None
2755+
2756+
Read-only, see :attr:`v1`.
2757+
2758+
:seealso: :attr:`v1` :meth:`connect`
2759+
"""
2760+
return self._v2
2761+
2762+
@v2.setter
2763+
def v2(self, value: BaseVertex | None) -> None:
2764+
raise AttributeError(_ENDPOINT_MESSAGE.format("v2"))
2765+
2766+
def _set_endpoints(self, v1: BaseVertex | None, v2: BaseVertex | None) -> None:
2767+
"""
2768+
Bind the edge to its vertices, or unbind it (private method)
2769+
2770+
Only the library calls this: the constructor's own assignment, then
2771+
:meth:`connect`, :meth:`BaseVertex.connect` for an edge built without
2772+
vertices, and :meth:`_BaseGraph.remove_edge`, which clears them.
2773+
"""
2774+
self._v1 = v1
2775+
self._v2 = v2
2776+
27202777
def __repr__(self) -> str:
27212778
"""
27222779
Detailed representation of the edge
@@ -2804,8 +2861,7 @@ def connect(self, v1: BaseVertex, v2: BaseVertex) -> None:
28042861
raise ValueError("vertices must belong to the same graph")
28052862

28062863
# connect edge to its vertices
2807-
self.v1 = v1
2808-
self.v2 = v2
2864+
self._set_endpoints(v1, v2)
28092865

28102866
# tell the vertices to add edge to their edgelists as appropriate for
28112867
# DGraph or UGraph
@@ -3279,8 +3335,7 @@ def _bind_edge(self, edge: Edge, dest: BaseVertex) -> None:
32793335
endpoints disagree with the vertices' edge lists.
32803336
"""
32813337
if edge.v1 is None and edge.v2 is None:
3282-
edge.v1 = self
3283-
edge.v2 = dest
3338+
edge._set_endpoints(self, dest)
32843339
elif not self._endpoints_match(edge, dest):
32853340
raise ValueError(
32863341
f"edge already connects {edge.v1} and {edge.v2}, "

‎tests/test_edge_endpoints.py‎

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
"""
2+
``Edge.v1`` and ``Edge.v2`` are read-only.
3+
4+
They used to be plain attributes, so a caller could write ``e.v1 = None`` on an
5+
edge that was in a graph and leave it wedged: ``remove_edge`` and
6+
``remove_vertex`` then raised and the edge could not be removed. Only the
7+
library binds an edge to its vertices -- the constructor, ``connect()`` and
8+
``remove_edge()`` -- so an edge in a graph always has both of its ends.
9+
"""
10+
11+
import copy
12+
import unittest
13+
14+
from pgraph import DGraph, Edge, UGraph
15+
16+
17+
class TestReadOnly(unittest.TestCase):
18+
def setUp(self):
19+
self.g = UGraph()
20+
self.a = self.g.add_vertex([0, 0], name="a")
21+
self.b = self.g.add_vertex([1, 0], name="b")
22+
self.c = self.g.add_vertex([2, 0], name="c")
23+
self.e = self.a.connect(self.b)
24+
25+
def test_cannot_assign(self):
26+
for name, value in (("v1", None), ("v1", self.c), ("v2", None), ("v2", self.c)):
27+
with self.subTest(name=name, value=value):
28+
with self.assertRaises(AttributeError) as cm:
29+
setattr(self.e, name, value)
30+
# the message says what to do instead
31+
self.assertIn("connect", str(cm.exception))
32+
33+
def test_cannot_delete(self):
34+
with self.assertRaises(AttributeError):
35+
del self.e.v1
36+
37+
def test_failed_assignment_changes_nothing(self):
38+
with self.assertRaises(AttributeError):
39+
self.e.v1 = self.c
40+
self.assertIs(self.e.v1, self.a)
41+
self.assertIs(self.e.v2, self.b)
42+
self.assertEqual(self.a.edges(), [self.e])
43+
self.assertEqual(self.c.edges(), [])
44+
45+
def test_the_graph_can_always_remove_its_edges(self):
46+
for name in ("v1", "v2"):
47+
try:
48+
setattr(self.e, name, None)
49+
except AttributeError:
50+
pass
51+
self.g.remove_edge(self.e) # not wedged
52+
self.assertEqual(self.g.ne, 0)
53+
self.g.remove_vertex(self.a)
54+
self.assertEqual(self.g.n, 2)
55+
56+
57+
class TestLibraryStillBindsThem(unittest.TestCase):
58+
def test_constructor(self):
59+
g = DGraph()
60+
a, b = g.add_vertex(name="a"), g.add_vertex(name="b")
61+
e = Edge(a, b, cost=3)
62+
self.assertIs(e.v1, a)
63+
self.assertIs(e.v2, b)
64+
65+
def test_standalone_edge_has_no_vertices(self):
66+
e = Edge(cost=1)
67+
self.assertIsNone(e.v1)
68+
self.assertIsNone(e.v2)
69+
70+
def test_connect_binds_a_bare_edge(self):
71+
g = UGraph()
72+
a, b = g.add_vertex(name="a"), g.add_vertex(name="b")
73+
e = Edge(cost=1)
74+
a.connect(b, edge=e)
75+
self.assertEqual((e.v1, e.v2), (a, b))
76+
77+
def test_edge_connect_binds(self):
78+
g = UGraph()
79+
a, b = g.add_vertex(name="a"), g.add_vertex(name="b")
80+
e = Edge(cost=1)
81+
e.connect(a, b)
82+
self.assertEqual((e.v1, e.v2), (a, b))
83+
84+
def test_removal_unlinks_and_the_edge_can_be_reused(self):
85+
g = UGraph()
86+
a, b, c = (g.add_vertex(name=n) for n in "abc")
87+
e = a.connect(b)
88+
g.remove_edge(e)
89+
self.assertIsNone(e.v1)
90+
self.assertIsNone(e.v2)
91+
with self.assertRaises(ValueError):
92+
g.add_edge(e) # unlinked, so add_edge(edge) refuses it
93+
b.connect(c, edge=e) # but connect() re-binds it
94+
self.assertEqual((e.v1, e.v2), (b, c))
95+
self.assertEqual(g.ne, 1)
96+
97+
def test_subclass_that_calls_super(self):
98+
class Observation(Edge):
99+
def __init__(self, v1, v2, uv):
100+
super().__init__(v1, v2, cost=0)
101+
self.uv = uv
102+
103+
g = UGraph()
104+
a, b = g.add_vertex(name="a"), g.add_vertex(name="b")
105+
o = Observation(a, b, (1, 2))
106+
a.connect(b, edge=o)
107+
self.assertEqual((o.v1, o.v2, o.uv), (a, b, (1, 2)))
108+
109+
def test_repr_and_copies_keep_the_endpoints(self):
110+
g = UGraph()
111+
a, b = g.add_vertex(name="a"), g.add_vertex(name="b")
112+
e = a.connect(b, cost=2)
113+
self.assertIn("a", str(e))
114+
for dup in (copy.copy(e), copy.deepcopy(e)):
115+
self.assertEqual(dup.cost, 2)
116+
self.assertIsNotNone(dup.v1)
117+
self.assertIsNotNone(dup.v2)
118+
119+
120+
if __name__ == "__main__":
121+
unittest.main()

0 commit comments

Comments
 (0)