Skip to content

Commit 0566a68

Browse files
authored
Merge pull request #28 from petercorke/fix/getitem-type-check
fix: graph[x] returned None for NumPy integers and other types
2 parents b6e799a + c30f1f1 commit 0566a68

2 files changed

Lines changed: 84 additions & 7 deletions

File tree

‎src/pgraph/PGraph.py‎

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -915,16 +915,21 @@ def __getitem__(self, i: int | str | BaseVertex) -> BaseVertex:
915915
Get vertex (base class method)
916916
917917
:param i: vertex description
918-
:type i: int or str
918+
:type i: int, str or BaseVertex subclass
919+
:raises IndexError: ``i`` is an integer outside the range of vertices
920+
:raises KeyError: ``i`` is a name that is not in the graph
921+
:raises TypeError: ``i`` is none of the types above
919922
:return: the referenced vertex
920923
:rtype: BaseVertex subclass
921924
922925
Retrieve a vertex by index or name:
923926
924-
-``g[i]`` is the i'th vertex in the graph. This reflects the order of
925-
addition to the graph.
926-
-``g[s]`` is vertex named ``s``
927-
-``g[v]`` is ``v`` where ``v`` is a ``BaseVertex`` subclass
927+
- ``g[i]`` is the i'th vertex in the graph. This reflects the order of
928+
addition to the graph. ``i`` can be any integer, including a NumPy
929+
integer such as the result of ``np.argmin()``, and a negative
930+
``i`` counts from the last vertex.
931+
- ``g[s]`` is vertex named ``s``
932+
- ``g[v]`` is ``v`` where ``v`` is a ``BaseVertex`` subclass
928933
929934
This method also supports iteration over the vertices in a graph::
930935
@@ -933,12 +938,16 @@ def __getitem__(self, i: int | str | BaseVertex) -> BaseVertex:
933938
934939
will iterate over all the vertices.
935940
"""
936-
if isinstance(i, int):
937-
return self._vertexlist[i]
941+
if isinstance(i, (int, np.integer)):
942+
return self._vertexlist[int(i)]
938943
elif isinstance(i, str):
939944
return self._vertexdict[i]
940945
elif isinstance(i, BaseVertex):
941946
return i
947+
else:
948+
raise TypeError(
949+
f"vertex must be an int, str or BaseVertex, got {type(i).__name__}"
950+
)
942951

943952
def __iter__(self) -> Iterator[BaseVertex]:
944953
"""

‎tests/test_getitem.py‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
"""
2+
``graph[x]`` resolves an index, a name or a vertex, and says so clearly when it
3+
cannot -- it must never quietly hand back ``None``.
4+
"""
5+
6+
import unittest
7+
8+
import numpy as np
9+
10+
from pgraph import DGraph, UGraph
11+
12+
13+
class _GetItem:
14+
Graph: type
15+
16+
def setUp(self):
17+
self.g = self.Graph()
18+
self.a = self.g.add_vertex([0, 0], name="a")
19+
self.b = self.g.add_vertex([1, 0], name="b")
20+
self.c = self.g.add_vertex([2, 0], name="c")
21+
22+
def test_int(self):
23+
self.assertIs(self.g[0], self.a)
24+
self.assertIs(self.g[2], self.c)
25+
self.assertIs(self.g[-1], self.c)
26+
27+
def test_numpy_integer(self):
28+
# e.g. the result of np.argmin(), a very common way to get an index
29+
self.assertIs(self.g[np.int64(1)], self.b)
30+
self.assertIs(self.g[np.argmin([3.0, 1.0, 2.0])], self.b)
31+
32+
def test_name(self):
33+
self.assertIs(self.g["b"], self.b)
34+
35+
def test_vertex(self):
36+
self.assertIs(self.g[self.c], self.c)
37+
38+
def test_unknown_name(self):
39+
with self.assertRaises(KeyError):
40+
self.g["zz"]
41+
42+
def test_index_out_of_range(self):
43+
with self.assertRaises(IndexError):
44+
self.g[3]
45+
with self.assertRaises(IndexError):
46+
self.g[-4]
47+
48+
def test_wrong_type(self):
49+
for bad in (1.5, None, [0], (0,), slice(0, 2), 1 + 2j):
50+
with self.subTest(bad=bad):
51+
with self.assertRaises(TypeError):
52+
self.g[bad]
53+
54+
def test_membership_and_iteration_unaffected(self):
55+
self.assertIn("a", self.g)
56+
self.assertEqual([v.name for v in self.g], ["a", "b", "c"])
57+
58+
59+
class TestUGraphGetItem(_GetItem, unittest.TestCase):
60+
Graph = UGraph
61+
62+
63+
class TestDGraphGetItem(_GetItem, unittest.TestCase):
64+
Graph = DGraph
65+
66+
67+
if __name__ == "__main__":
68+
unittest.main()

0 commit comments

Comments
 (0)