Skip to content

Commit 8cf0d2d

Browse files
petercorkeclaude
andcommitted
fix: add_vertex refuses a duplicate name, and chooses a free default name
Names are how g[name] finds a vertex, so they must be unique in a graph. - adding a vertex whose name is already used raised nothing and replaced the earlier vertex in the name table, leaving it in the graph but unreachable by name; it now raises ValueError and changes nothing - the default name #N used the number of vertices, so after a removal it could equal an existing name (remove #0 from #0 #1 #2, add one: #2 twice); it now takes the first #N that is free - a vertex that already belongs to a graph, this one or another, could be added: it was then listed by both. It now raises ValueError; a removed vertex can be added again, or elsewhere - every check precedes any change, so a refused add leaves the graph and the vertex exactly as they were Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent 4613e04 commit 8cf0d2d

2 files changed

Lines changed: 141 additions & 2 deletions

File tree

‎src/pgraph/PGraph.py‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -522,6 +522,8 @@ def add_vertex(
522522
:type name: str, optional
523523
:raises TypeError: ``coord`` is a ``BaseVertex`` that is not an
524524
instance of this graph's :attr:`vertex_class`
525+
:raises ValueError: the name is already used by another vertex in the
526+
graph, or ``coord`` is a vertex that already belongs to a graph
525527
:raises ValueError: the graph was constructed with ``dim``, and
526528
``coord`` is given but its length doesn't match
527529
:return: the added vertex
@@ -535,7 +537,17 @@ def add_vertex(
535537
to the graph.
536538
537539
If the vertex has no name and ``name`` is None give it a default name
538-
``#N`` where ``N`` is a consecutive integer.
540+
``#N`` where ``N`` is the number of vertices, or the next integer above
541+
it that is not already used by a name in the graph.
542+
543+
Names are unique within a graph, since they are how ``g[name]`` finds a
544+
vertex, and a vertex belongs to one graph at a time.
545+
546+
.. versionchanged:: 1.0
547+
Adding a vertex whose name is already used raises ``ValueError``.
548+
It used to replace the earlier vertex in the name table, leaving it
549+
in the graph but unreachable by name. A default name could also
550+
clash with an existing one after a vertex had been removed.
539551
540552
The vertex is placed into a dictionary with a key equal to its name.
541553
@@ -569,6 +581,11 @@ def add_vertex(
569581
"""
570582
if isinstance(coord, self._vertex_class):
571583
vertex = coord
584+
if vertex._graph is not None:
585+
raise ValueError(
586+
f"vertex {vertex.name!r} already belongs to a graph; "
587+
"remove it from that graph first"
588+
)
572589
elif isinstance(coord, BaseVertex):
573590
raise TypeError(
574591
f"expecting {self._vertex_class.__name__} or coordinate data, "
@@ -590,7 +607,13 @@ def add_vertex(
590607
if name is None:
591608
name = vertex.name
592609
if name is None:
593-
name = f"#{len(self._vertexlist)}"
610+
# the first #N not already used: a removal makes len() reuse a name
611+
n = len(self._vertexlist)
612+
while f"#{n}" in self._vertexdict:
613+
n += 1
614+
name = f"#{n}"
615+
elif name in self._vertexdict:
616+
raise ValueError(f"the graph already has a vertex named {name!r}")
594617
vertex.name = name
595618
self._vertexlist.append(vertex)
596619
self._vertexdict[vertex.name] = vertex

‎tests/test_add_vertex_names.py‎

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
"""
2+
A graph's vertices have unique names (the name is the key ``g[name]`` looks
3+
them up by), and a vertex belongs to at most one graph. ``add_vertex`` used to
4+
overwrite the earlier vertex's table entry on a clash, and the default
5+
``#N`` names could clash after a removal; it now refuses, and chooses a default
6+
name that is free.
7+
"""
8+
9+
import unittest
10+
11+
from pgraph import DGraph, UGraph, UVertex
12+
13+
14+
class _AddVertex:
15+
Graph: type
16+
Vertex: type
17+
18+
def setUp(self):
19+
self.g = self.Graph()
20+
21+
def snapshot(self, g):
22+
return (g.n, sorted(g._vertexdict), [v.name for v in g])
23+
24+
def test_duplicate_name_is_refused(self):
25+
a = self.g.add_vertex(name="a")
26+
before = self.snapshot(self.g)
27+
with self.assertRaises(ValueError) as cm:
28+
self.g.add_vertex(name="a")
29+
self.assertIn("'a'", str(cm.exception))
30+
self.assertEqual(self.snapshot(self.g), before)
31+
self.assertIs(self.g["a"], a)
32+
self.assertEqual(self.g.validate(), [])
33+
34+
def test_duplicate_through_a_vertex_instance(self):
35+
self.g.add_vertex(name="a")
36+
clash = self.Vertex([1, 1], name="a")
37+
with self.assertRaises(ValueError):
38+
self.g.add_vertex(clash)
39+
self.assertIsNone(clash._graph) # untouched: not half added
40+
self.assertEqual(self.g.n, 1)
41+
42+
def test_name_argument_overriding_the_instance_name_is_checked_too(self):
43+
self.g.add_vertex(name="taken")
44+
v = self.Vertex([0, 0], name="free")
45+
with self.assertRaises(ValueError):
46+
self.g.add_vertex(v, name="taken")
47+
self.assertEqual(v.name, "free") # a refused add does not rename it
48+
49+
def test_default_names_are_unique_after_removals(self):
50+
vs = [self.g.add_vertex() for _ in range(4)] # #0 .. #3
51+
self.g.remove_vertex(vs[0])
52+
self.g.remove_vertex(vs[2])
53+
more = [self.g.add_vertex() for _ in range(3)]
54+
names = [v.name for v in self.g]
55+
self.assertEqual(len(names), len(set(names)))
56+
self.assertEqual(self.g.n, 5)
57+
self.assertEqual(self.g.validate(), [])
58+
for v in more:
59+
self.assertIs(self.g[v.name], v)
60+
61+
def test_default_name_skips_one_given_explicitly(self):
62+
self.g.add_vertex(name="#1")
63+
a = self.g.add_vertex()
64+
b = self.g.add_vertex()
65+
self.assertEqual(len({"#1", a.name, b.name}), 3)
66+
self.assertEqual(self.g.validate(), [])
67+
68+
def test_default_names_still_count_from_zero(self):
69+
self.assertEqual([self.g.add_vertex().name for _ in range(3)], ["#0", "#1", "#2"])
70+
71+
def test_a_vertex_in_this_graph_cannot_be_added_again(self):
72+
a = self.g.add_vertex(name="a")
73+
with self.assertRaises(ValueError):
74+
self.g.add_vertex(a)
75+
self.assertEqual(self.g.n, 1)
76+
self.assertEqual(self.g.validate(), [])
77+
78+
def test_a_vertex_in_another_graph_cannot_be_added(self):
79+
other = self.Graph()
80+
v = other.add_vertex(name="v")
81+
with self.assertRaises(ValueError):
82+
self.g.add_vertex(v)
83+
self.assertIs(v._graph, other) # still where it was
84+
self.assertEqual(other.validate(), [])
85+
self.assertEqual(self.g.n, 0)
86+
87+
def test_a_removed_vertex_can_be_added_again_or_elsewhere(self):
88+
a = self.g.add_vertex(name="a")
89+
self.g.remove_vertex(a)
90+
self.assertIs(self.g.add_vertex(a), a)
91+
self.g.remove_vertex(a)
92+
other = self.Graph()
93+
self.assertIs(other.add_vertex(a), a)
94+
self.assertEqual(other.validate(), [])
95+
96+
def test_wrong_dimension_changes_nothing(self):
97+
g = self.Graph(dim=3)
98+
v = self.Vertex([1, 2], name="short")
99+
with self.assertRaises(ValueError):
100+
g.add_vertex(v)
101+
self.assertEqual(g.n, 0)
102+
self.assertIsNone(v._graph)
103+
104+
105+
class TestUGraph(_AddVertex, unittest.TestCase):
106+
Graph, Vertex = UGraph, UVertex
107+
108+
109+
class TestDGraph(_AddVertex, unittest.TestCase):
110+
from pgraph import DVertex as Vertex
111+
112+
Graph = DGraph
113+
114+
115+
if __name__ == "__main__":
116+
unittest.main()

0 commit comments

Comments
 (0)