Skip to content

Commit a063fb2

Browse files
petercorkeclaude
andcommitted
refactor: graph.edges() returns a list in order of addition, and both edges() methods return copies
BaseGraph.edges() returned the graph's own set of edges (documented as a list), so it had no order, and it, like BaseVertex.edges(), handed out the live container: clearing the result emptied the graph's records without updating ne, and removing edges while iterating skipped some. The graph now keeps its edges in a dict used as an insertion-ordered set (keyed by the edge object, hashed by identity), so removal is still O(1), and both edges() methods return a new list. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent eb78442 commit a063fb2

6 files changed

Lines changed: 152 additions & 34 deletions

File tree

‎src/pgraph/PGraph.py‎

Lines changed: 45 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,10 @@ def __init__(
105105
# we use a list and a dict, the list respects the order of adding
106106
self._vertexlist: list[BaseVertex] = []
107107
self._vertexdict: dict[str, BaseVertex] = {}
108-
self._edgelist: set[Edge] = set()
108+
# an insertion-ordered set: the keys are the edges, hashed by identity
109+
# (Edge defines no __eq__), the values are unused. This gives O(1)
110+
# removal and a defined order.
111+
self._edges: dict[Edge, None] = {}
109112
self._verbose = verbose
110113
self._dim = dim
111114
self._ncomponents = 0
@@ -377,11 +380,11 @@ def validate(self) -> list[str]:
377380
else:
378381
problems.append(f"the vertex list holds {entry!r}, which is not a vertex")
379382
graph_edges: list[Edge] = []
380-
for member in self._edgelist:
383+
for member in self._edges:
381384
if isinstance(member, Edge):
382385
graph_edges.append(member)
383386
else:
384-
problems.append(f"the edge set holds {member!r}, which is not an edge")
387+
problems.append(f"the graph's edges hold {member!r}, which is not an edge")
385388

386389
# ---- vertices
387390
members = {id(v) for v in vertices}
@@ -844,7 +847,7 @@ def remove_edge(self, edge: Edge) -> None:
844847
845848
:seealso: :meth:`remove_vertex` :meth:`Edge.remove`
846849
"""
847-
if edge not in self._edgelist:
850+
if edge not in self._edges:
848851
raise ValueError("edge does not belong to this graph")
849852
v1, v2 = edge.v1, edge.v2
850853
if v1 is None or v2 is None:
@@ -860,7 +863,7 @@ def remove_edge(self, edge: Edge) -> None:
860863

861864
edge._set_endpoints(None, None)
862865

863-
self._edgelist.remove(edge)
866+
del self._edges[edge]
864867

865868
def remove_vertex(self, vertex: BaseVertex) -> None:
866869
"""
@@ -951,7 +954,7 @@ def show(self) -> None:
951954
for v in self._vertexlist:
952955
print(" " + str(v))
953956
print("edges:")
954-
for e in self._edgelist:
957+
for e in self._edges:
955958
print(" " + str(e))
956959

957960
@property
@@ -989,7 +992,7 @@ def ne(self) -> int:
989992
>>> g.add_edge(v1, v2)
990993
>>> print(g.ne)
991994
"""
992-
return len(self._edgelist)
995+
return len(self._edges)
993996

994997
@abstractmethod
995998
def _graphcolor(self) -> int | None:
@@ -1327,21 +1330,35 @@ def closest(self, coord: ArrayLike) -> tuple[BaseVertex | None, float]:
13271330

13281331
return min_which, min_dist
13291332

1330-
def edges(self) -> set[Edge]:
1333+
def edges(self) -> list[Edge]:
13311334
"""
13321335
Get all edges in graph (base class method)
13331336
13341337
:return: All edges in the graph
1335-
:rtype: set of Edge references
1338+
:rtype: list of Edge references
1339+
1340+
The edges are in the order they were added to the graph. This is a
1341+
new list, so it can be modified or sorted without affecting the graph,
1342+
and edges can be removed from the graph while iterating over it.
13361343
13371344
We can iterate over all edges in the graph by::
13381345
13391346
for e in g.edges():
13401347
print(e)
13411348
1342-
.. note:: Unlike :meth:`BaseVertex.edges`, which returns a ``list`` in
1343-
connection order, this returns a ``set`` with no defined
1344-
iteration order.
1349+
and select one by index, for example the second edge added is
1350+
``g.edges()[1]``.
1351+
1352+
.. note:: Like :meth:`BaseVertex.edges` this is a ``list``, but where
1353+
that lists the edges attached to one vertex, this lists every edge
1354+
in the graph once. A self-loop is one edge here, but appears
1355+
twice in the :meth:`BaseVertex.edges` of an undirected vertex
1356+
because it has two ends there.
1357+
1358+
.. versionchanged:: 1.0
1359+
Returns a ``list`` in order of addition. In 0.6.5 this was the
1360+
graph's own ``set``, with no defined order, although the
1361+
documentation said ``list``.
13451362
13461363
.. runblock:: pycon
13471364
@@ -1352,9 +1369,9 @@ def edges(self) -> set[Edge]:
13521369
>>> g.add_edge(v1, v2)
13531370
>>> print(g.edges())
13541371
1355-
:seealso: :meth:`BaseVertex.edges`
1372+
:seealso: :meth:`BaseVertex.edges` :attr:`ne`
13561373
"""
1357-
return self._edgelist
1374+
return list(self._edges)
13581375

13591376
def plot(
13601377
self,
@@ -2224,14 +2241,14 @@ def incidence(self) -> NDArray:
22242241
.. note::
22252242
- vertices are numbered in their order of creation. A vertex index
22262243
can be resolved to a vertex reference by ``graph[i]``.
2227-
- edges are numbered in the order they appear in ``graph.edges()``.
2244+
- edges are numbered in the order they appear in :meth:`edges`, which
2245+
is the order they were added.
22282246
- Both endpoints of every edge are marked, regardless of
22292247
direction -- for a ``DGraph`` this means a vertex that is only
2230-
ever a target (never a source) still appears here, unlike
2231-
:meth:`degree`/:attr:`BaseVertex.degree`, which count outgoing
2232-
edges only. Iterating each vertex's own
2233-
:meth:`BaseVertex.edges` instead would silently drop such
2234-
vertices for a directed graph.
2248+
ever a target (never a source) still appears here. Iterating
2249+
each vertex's own :meth:`BaseVertex.edges`, which are its
2250+
outgoing edges, would silently drop such vertices for a
2251+
directed graph.
22352252
22362253
.. rubric:: For graphs with parallel edges or loops
22372254
@@ -3541,7 +3558,7 @@ def connect(
35413558
else:
35423559
e = self._graph._edge_class(self, dest, cost=cost, data=data)
35433560

3544-
self._graph._edgelist.add(e)
3561+
self._graph._edges[e] = None
35453562
self._graph._connectivitychange = True
35463563
self._connectivitychange = True
35473564

@@ -3661,11 +3678,16 @@ def edges(self) -> list[Edge]:
36613678
:return: List of all edges leaving this vertex
36623679
:rtype: list of Edge
36633680
3681+
The edges are in the order they were connected. This is a new list,
3682+
so it can be modified, and edges can be removed from the graph while
3683+
iterating over it.
3684+
36643685
.. note::
36653686
36663687
- For a directed graph the edges are those leaving this vertex
36673688
- For a non-directed graph the edges are those leaving or entering
3668-
this vertex
3689+
this vertex, and a self-loop is listed twice, once for each of
3690+
its ends
36693691
36703692
.. runblock:: pycon
36713693
@@ -3679,7 +3701,7 @@ def edges(self) -> list[Edge]:
36793701
:seealso: :meth:`out_edges` :meth:`in_edges` :meth:`adjacent`
36803702
:meth:`incidences` :attr:`degree` :meth:`BaseGraph.edges`
36813703
"""
3682-
return self._edgelist
3704+
return list(self._edgelist)
36833705

36843706
def heuristic_distance(self, v2: BaseVertex) -> float:
36853707
"""

‎src/pgraph/exporters.py‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -141,12 +141,11 @@ def _ordered_edges(graph: BaseGraph) -> list[tuple[Edge, BaseVertex, BaseVertex]
141141
"""
142142
Edges in a reproducible order
143143
144-
``graph.edges()`` is a set, so its order changes from run to run and the
145-
exported text would not be stable (useless for diffs and golden files).
146-
Instead walk the vertices in creation order and each vertex's own
147-
outgoing edges, keeping the first sight of every edge. Identity is by object, not by
148-
endpoints, so parallel edges are all kept, and an undirected edge (held by
149-
both ends, twice for a self-loop) is listed once.
144+
Walk the vertices in creation order and each vertex's own outgoing edges,
145+
keeping the first sight of every edge, so that edges are grouped by the
146+
vertex they leave. Identity is by object, not by endpoints, so parallel
147+
edges are all kept, and an undirected edge (held by both ends, twice for a
148+
self-loop) is listed once.
150149
151150
Each item is ``(edge, start, end)``.
152151
"""

‎tests/test_edges_list.py‎

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
"""``graph.edges()`` and ``vertex.edges()`` return new lists in order of addition.
2+
3+
In 0.6.5 ``graph.edges()`` returned the graph's own ``set`` (documented as a
4+
list), so it had no order, and either method returned the live container, so
5+
a caller could corrupt the graph by modifying the result.
6+
"""
7+
8+
import unittest
9+
10+
from pgraph import DGraph, UGraph
11+
12+
13+
class _EdgesList:
14+
cls: type
15+
16+
def setUp(self):
17+
self.g = self.cls()
18+
self.a, self.b, self.c = (self.g.add_vertex() for _ in range(3))
19+
self.e1 = self.g.add_edge(self.a, self.b)
20+
self.e2 = self.g.add_edge(self.b, self.c)
21+
self.e3 = self.g.add_edge(self.a, self.c)
22+
23+
def test_is_a_list_in_order_of_addition(self):
24+
edges = self.g.edges()
25+
self.assertIsInstance(edges, list)
26+
self.assertEqual(edges, [self.e1, self.e2, self.e3])
27+
28+
def test_order_survives_removal(self):
29+
self.g.remove_edge(self.e2)
30+
e4 = self.g.add_edge(self.b, self.c)
31+
self.assertEqual(self.g.edges(), [self.e1, self.e3, e4])
32+
33+
def test_graph_result_is_a_copy(self):
34+
self.g.edges().clear()
35+
self.assertEqual(self.g.ne, 3)
36+
self.assertEqual(self.g.edges(), [self.e1, self.e2, self.e3])
37+
self.assertEqual(self.g.validate(), [])
38+
39+
def test_vertex_result_is_a_copy(self):
40+
self.a.edges().clear()
41+
self.assertEqual(len(self.a.edges()), 2)
42+
self.assertEqual(self.g.validate(), [])
43+
44+
def test_remove_while_iterating_visits_every_edge(self):
45+
seen = []
46+
for e in self.g.edges():
47+
seen.append(e)
48+
self.g.remove_edge(e)
49+
self.assertEqual(seen, [self.e1, self.e2, self.e3])
50+
self.assertEqual(self.g.ne, 0)
51+
52+
def test_vertex_remove_while_iterating_visits_every_edge(self):
53+
seen = []
54+
for e in self.a.edges():
55+
seen.append(e)
56+
self.g.remove_edge(e)
57+
self.assertEqual(seen, [self.e1, self.e3])
58+
self.assertEqual(self.a.edges(), [])
59+
60+
def test_parallel_edges_are_both_listed(self):
61+
e4 = self.g.add_edge(self.a, self.b)
62+
self.assertEqual(self.g.edges().count(e4), 1)
63+
self.assertEqual(len(self.g.edges()), 4)
64+
self.assertEqual(self.g.ne, 4)
65+
66+
def test_loop_is_one_graph_edge(self):
67+
loop = self.g.add_edge(self.c, self.c)
68+
self.assertEqual(self.g.edges().count(loop), 1)
69+
self.assertEqual(self.g.ne, 4)
70+
71+
def test_edge_removed_via_edge_leaves_the_list(self):
72+
self.e1.remove()
73+
self.assertEqual(self.g.edges(), [self.e2, self.e3])
74+
75+
def test_vertex_removal_removes_its_edges(self):
76+
self.g.remove_vertex(self.b)
77+
self.assertEqual(self.g.edges(), [self.e3])
78+
79+
80+
class TestUGraphEdgesList(_EdgesList, unittest.TestCase):
81+
cls = UGraph
82+
83+
def test_loop_is_listed_twice_at_its_vertex(self):
84+
loop = self.g.add_edge(self.c, self.c)
85+
self.assertEqual(self.c.edges().count(loop), 2)
86+
87+
88+
class TestDGraphEdgesList(_EdgesList, unittest.TestCase):
89+
cls = DGraph
90+
91+
def test_loop_is_listed_once_at_its_vertex(self):
92+
loop = self.g.add_edge(self.c, self.c)
93+
self.assertEqual(self.c.edges().count(loop), 1)
94+
95+
96+
if __name__ == "__main__":
97+
unittest.main()

‎tests/test_multigraph.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
"""
22
Self-loops and parallel edges.
33
4-
pgraph does not forbid either, so every quantity derived from the edge set
4+
pgraph does not forbid either, so every quantity derived from the graph's edges
55
(degree, the matrix representations, cycle detection, path planning) has to
66
give a defined, consistent answer when they are present.
77

‎tests/test_validate.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -178,7 +178,7 @@ def test_junk_in_the_containers_is_reported_not_raised(self):
178178
# validate() is for finding corruption, so it must survive it
179179
g, a, b, c, d = build(UGraph)
180180
g._vertexlist.append("junk")
181-
g._edgelist.add(42)
181+
g._edges[42] = None
182182
a._edgelist.append("junk")
183183
msg = self.problems(g)
184184
for word in ("junk", "42", "not a vertex", "not an edge"):
@@ -209,14 +209,14 @@ class MyEdge(Edge):
209209
g = UGraph(edge_class=MyEdge)
210210
a, b = g.add_vertex(name="a"), g.add_vertex(name="b")
211211
e = Edge(a, b)
212-
g._edgelist.add(e)
212+
g._edges[e] = None
213213
a._edgelist.append(e)
214214
b._edgelist.append(e)
215215
self.assertIn("MyEdge", self.problems(g))
216216

217217
def test_vertex_list_entry_for_an_edge_removed_from_the_graph(self):
218218
g, a, b, c, d = build(UGraph)
219-
g._edgelist.discard(a.edges()[0])
219+
g._edges.pop(a.edges()[0], None)
220220
self.assertIn("not in the graph", self.problems(g))
221221

222222
def test_self_loop_held_once_instead_of_twice(self):

‎tests/test_vertex_hook.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ class Recording(self.Vertex):
5959
def _attach(self, edge, dest):
6060
# the edge is already registered with the graph at this point
6161
outer.calls.append(
62-
(self, edge, dest, edge in self._graph._edgelist)
62+
(self, edge, dest, edge in self._graph._edges)
6363
)
6464
super()._attach(edge, dest)
6565

0 commit comments

Comments
 (0)