Skip to content

Commit 26937cf

Browse files
petercorkeclaude
andcommitted
fix: graph[x] raised nothing for NumPy integers or other types
__getitem__ fell off the end and returned None for anything that was not a Python int, str or vertex -- including np.int64, so g[np.argmin(d)] quietly gave None. NumPy integers are now accepted, and any other type raises TypeError. Exceptions are documented. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent d03b828 commit 26937cf

1 file changed

Lines changed: 16 additions & 7 deletions

File tree

‎src/pgraph/PGraph.py‎

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -852,16 +852,21 @@ def __getitem__(self, i: int | str | BaseVertex) -> BaseVertex:
852852
Get vertex (base class method)
853853
854854
:param i: vertex description
855-
:type i: int or str
855+
:type i: int, str or BaseVertex subclass
856+
:raises IndexError: ``i`` is an integer outside the range of vertices
857+
:raises KeyError: ``i`` is a name that is not in the graph
858+
:raises TypeError: ``i`` is none of the types above
856859
:return: the referenced vertex
857860
:rtype: BaseVertex subclass
858861
859862
Retrieve a vertex by index or name:
860863
861-
-``g[i]`` is the i'th vertex in the graph. This reflects the order of
862-
addition to the graph.
863-
-``g[s]`` is vertex named ``s``
864-
-``g[v]`` is ``v`` where ``v`` is a ``BaseVertex`` subclass
864+
- ``g[i]`` is the i'th vertex in the graph. This reflects the order of
865+
addition to the graph. ``i`` can be any integer, including a NumPy
866+
integer such as the result of ``np.argmin()``, and a negative
867+
``i`` counts from the last vertex.
868+
- ``g[s]`` is vertex named ``s``
869+
- ``g[v]`` is ``v`` where ``v`` is a ``BaseVertex`` subclass
865870
866871
This method also supports iteration over the vertices in a graph::
867872
@@ -870,12 +875,16 @@ def __getitem__(self, i: int | str | BaseVertex) -> BaseVertex:
870875
871876
will iterate over all the vertices.
872877
"""
873-
if isinstance(i, int):
874-
return self._vertexlist[i]
878+
if isinstance(i, (int, np.integer)):
879+
return self._vertexlist[int(i)]
875880
elif isinstance(i, str):
876881
return self._vertexdict[i]
877882
elif isinstance(i, BaseVertex):
878883
return i
884+
else:
885+
raise TypeError(
886+
f"vertex must be an int, str or BaseVertex, got {type(i).__name__}"
887+
)
879888

880889
def __iter__(self) -> Iterator[BaseVertex]:
881890
"""

0 commit comments

Comments
 (0)