From f1d03e9a853d5ebd68d099684c5c67cb9b886426 Mon Sep 17 00:00:00 2001 From: pmlpm1986 <96069104+pmlpm1986@users.noreply.github.com> Date: Tue, 6 Sep 2022 23:44:28 +0200 Subject: Change is_path to return False when node not in G instead of raising exception (#5943) Formerly, is_path raised a KeyError when one of the nodes in the input path was not actually in G. This PR modifies the function so that it returns False in this case instead of raising an exception. --- networkx/classes/function.py | 7 ++++++- networkx/classes/tests/test_function.py | 4 ++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/networkx/classes/function.py b/networkx/classes/function.py index fb24105f..a0807942 100644 --- a/networkx/classes/function.py +++ b/networkx/classes/function.py @@ -1279,7 +1279,10 @@ def number_of_selfloops(G): def is_path(G, path): - """Returns whether or not the specified path exists + """Returns whether or not the specified path exists. + + For it to return True, every node on the path must exist and + each consecutive pair must be connected via one or more edges. Parameters ---------- @@ -1296,6 +1299,8 @@ def is_path(G, path): """ for node, nbr in nx.utils.pairwise(path): + if node not in G: + return False if nbr not in G[node]: return False return True diff --git a/networkx/classes/tests/test_function.py b/networkx/classes/tests/test_function.py index 051d655c..df17f200 100644 --- a/networkx/classes/tests/test_function.py +++ b/networkx/classes/tests/test_function.py @@ -771,12 +771,16 @@ def test_pathweight(): def test_ispath(): valid_path = [1, 2, 3, 4] invalid_path = [1, 2, 4, 3] + another_invalid_path = [1, 2, 3, 4, 5] + yet_another_invalid_path = [1, 2, 5, 3, 4] graphs = [nx.Graph(), nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph()] edges = [(1, 2), (2, 3), (1, 2), (3, 4)] for graph in graphs: graph.add_edges_from(edges) assert nx.is_path(graph, valid_path) assert not nx.is_path(graph, invalid_path) + assert not nx.is_path(graph, another_invalid_path) + assert not nx.is_path(graph, yet_another_invalid_path) @pytest.mark.parametrize("G", (nx.Graph(), nx.DiGraph())) -- cgit v1.2.1