@@ -236,11 +236,18 @@ pub fn bfs_predecessors(
236236/// :rtype: set
237237#[ pyfunction]
238238#[ pyo3( text_signature = "(graph, node, /)" ) ]
239- pub fn ancestors ( graph : & digraph:: PyDiGraph , node : usize ) -> HashSet < usize > {
240- core_ancestors ( & graph. graph , NodeIndex :: new ( node) )
239+ pub fn ancestors ( graph : & digraph:: PyDiGraph , node : usize ) -> PyResult < HashSet < usize > > {
240+ let index = NodeIndex :: new ( node) ;
241+ if !graph. graph . contains_node ( index) {
242+ return Err ( PyIndexError :: new_err ( format ! (
243+ "Node source index \" {}\" out of graph bound" ,
244+ node
245+ ) ) ) ;
246+ }
247+ Ok ( core_ancestors ( & graph. graph , index)
241248 . map ( |x| x. index ( ) )
242249 . filter ( |x| * x != node)
243- . collect ( )
250+ . collect ( ) )
244251}
245252
246253/// Return the descendants of a node in a graph.
@@ -257,12 +264,18 @@ pub fn ancestors(graph: &digraph::PyDiGraph, node: usize) -> HashSet<usize> {
257264/// :rtype: set
258265#[ pyfunction]
259266#[ pyo3( text_signature = "(graph, node, /)" ) ]
260- pub fn descendants ( graph : & digraph:: PyDiGraph , node : usize ) -> HashSet < usize > {
267+ pub fn descendants ( graph : & digraph:: PyDiGraph , node : usize ) -> PyResult < HashSet < usize > > {
261268 let index = NodeIndex :: new ( node) ;
262- core_descendants ( & graph. graph , index)
269+ if !graph. graph . contains_node ( index) {
270+ return Err ( PyIndexError :: new_err ( format ! (
271+ "Node source index \" {}\" out of graph bound" ,
272+ node
273+ ) ) ) ;
274+ }
275+ Ok ( core_descendants ( & graph. graph , index)
263276 . map ( |x| x. index ( ) )
264277 . filter ( |x| * x != node)
265- . collect ( )
278+ . collect ( ) )
266279}
267280
268281/// Breadth-first traversal of a directed graph with several source vertices.
0 commit comments