Skip to content

Improving views exceptions - #8588

Merged
dschult merged 4 commits into
networkx:mainfrom
amcandio:views_exceptions
Apr 12, 2026
Merged

dschult merged 4 commits into
networkx:mainfrom
amcandio:views_exceptions

Conversation

@amcandio

@amcandio amcandio commented Mar 29, 2026 •

Copy link
Copy Markdown
Contributor

When debugging a KeyError in MultiDiGraph edges views, I got confused by the exception message refering to one specific node. For example:

>>> import networkx as nx
>>> G = nx.MultiDiGraph([(0, 1)])
>>> G.edges[1, 0, 42]
Traceback (most recent call last):
  File "<python-input-2>", line 1, in <module>
    G.edges[1, 0, 42]
    ~~~~~~~^^^^^^^^^^
  File "/Users/amcandio/workplace/networkx/networkx/classes/reportviews.py", line 1471, in __getitem__
    return self._adjdict[u][v][k]
           ~~~~~~~~~~~~~~~~^^^
KeyError: 0

That made me think that the node 0 was not present and misdirected my debugging efforts.

This PR standarizes KeyError messages across views so this one now shows:

KeyError: 'The edge (1, 0, 42) is not in the graph'

This is what originally motivated #8533 but here I just focus on the logging part (as it was what orignally caused my confusion!).

@rossbar rossbar left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AIUI, this PR only changes the exception messages, not the exception types (at least AFAICT). I'm generally +1 for more informative messages, and since the exception types are all consistent we shouldn't be breaking anyone's code!

Thanks @amcandio !

try:
return self._adjdict[u][v]
except KeyError as ex: # Customize msg to indicate exception origin
raise KeyError(f"The edge {e} is not in the graph.")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess the one subjective point is what the grammar should be for the exception messages. I'm personally fine on removing the period (and leaving periods off of all the newly-added messages) for consistency with the built-in exception messages.

I don't have an opinion one way or the other - just mentioning here in case others do!

@dschult

dschult commented Apr 10, 2026

Copy link
Copy Markdown
Member

Do we lose information here? The old error had a traceback that shows which part of the edge had a KeyError. And the KeyError message shows which node part of the edge led to the keyerror. Now we just get that the edge tuple caused an error, but we can't tell which part of it was the problem. The traceback show the except clause and the new KeyError message, but there is no information about the original KeyError.

You state that you thought

    return self._adjdict[u][v][k]
           ~~~~~~~~~~~~~~~~^^^
KeyError: 0

meant that node 0 was not present. And it isn't present -- in the dict returned by self._adjdict[u]. That doesn't mean it is not present in the dict self._adjdict.

Is there a way that we can change the error message to make it clear that the edge was not found, and still make it clear that the 2nd entry in the edge tuple was the trouble-maker? And I think we should retain the Traceback that shows where the error actually occurred. That is quite helpful when debugging. How do we change the message while keeping the old message and keeping the old traceback?

I'm also a little concerned about try/except slowing down the inner working of our dicts. It used to be a minor issue, but I'm not sure it is any more.

@dschult dschult left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ahh... I found it.
We can "add_note" to an exception message (as of Python 3.11) and if we use a bare raise it keeps the Traceback the same -- without adding the misdirection of having an exception raise another exception.

Comment thread networkx/classes/reportviews.py Resolved
@amcandio

Copy link
Copy Markdown
Contributor Author

Good idea, will add it on the relevant places!

@dschult dschult left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I checked the timing for these changes.
I don't see any change significant timing change in the nodeviews, but the edgeviews are consistently 10-15% slower. I'm just doing an ipython run in one branch and then switching branches and running it again. Using G=binomial_graph(500, 0.3) and then converting to DiGraph(G.edges) for the other 3 graph types.

In [10]: node_ratio
Out[10]: 
[1.0180193811817848,
 0.9928326001439324,
 0.9933429942939951,
 1.031412567801611]

In [11]: edge_ratio
Out[11]: 
[1.1344763924264316,
 1.1639668887977164,
 1.0999263146032279,
 1.0883453134196077]

The only thing I can figure is that pre-checking the length of the edge is eating up time. Do we need that? Isn't the standard error message for incorrect length clear? In fact it actually gives more information.

ValueError: not enough values to unpack (expected 2, got 1)
vs
ValueError: Edge must have length 2

I'm starting to lean against this PR. The current error messages have more information and the extra error checking makes the code uglier and takes longer. If I understand correctly, the advantage is that the new error messages talk about "edges" or "nodes". So you know that it is an edge lookup that failed. But isn't that clear from the traceback?

@amcandio

amcandio commented Apr 11, 2026 •

Copy link
Copy Markdown
Contributor Author

My main confusion as a user came from the KeyError refering to a node when the actual missing entity is the edge (I thought that a node was missing when it was not).

I reverted the node exception wrappers as they don't add much clarity and make the code uglier. With the current version we have:

In [1]: import networkx as nx

In [2]: G = nx.MultiDiGraph([(0, 1)])

In [3]: G.edges[1, 0, 42]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Cell In[3], line 1
----> 1 G.edges[1, 0, 42]

File ~/workplace/networkx/networkx/classes/reportviews.py:1479, in OutMultiEdgeView.__getitem__(self, e)
   1477 except KeyError as err:
   1478     err.add_note(f"The edge {e} is not in the graph")
-> 1479     raise err

File ~/workplace/networkx/networkx/classes/reportviews.py:1476, in OutMultiEdgeView.__getitem__(self, e)
   1474 u, v, k = e
   1475 try:
-> 1476     return self._adjdict[u][v][k]
   1477 except KeyError as err:
   1478     err.add_note(f"The edge {e} is not in the graph")

KeyError: 0
The edge (1, 0, 42) is not in the graph

which clarifies that the edge is the actualy entity missing.

I do not see regressions with the following benchmark:

import networkx as nx
import timeit

G = nx.binomial_graph(500, 0.3)
edges = G.edges

def bench(stmt, number=10):
    return timeit.timeit(stmt, number=number, globals=globals())

print("list(G.nodes):",
      bench("list(G.nodes)"))

print("list(G.edges):",
      bench("list(G.edges)"))

def consume_edges(G):
    s = 0
    for u, v in G.edges:
        s += u + v
    return s

print("edge unpack loop:",
      bench("consume_edges(G)"))

print("list(edges):",
      bench("list(edges)"))

print("Graph(G.edges):",
      bench("nx.Graph(G.edges)"))

print("DiGraph(G.edges):",
      bench("nx.DiGraph(G.edges)"))

print("MultiGraph(G.edges):",
      bench("nx.MultiGraph(G.edges)"))

print("MultiDiGraph(G.edges):",
      bench("nx.MultiDiGraph(G.edges)"))

@dschult

dschult commented Apr 12, 2026 •

Copy link
Copy Markdown
Member

Thanks for those benchmarks -- and for hearing my concerns.
I think those benchmarks time the iterator code, which didn't change as far as I can tell.
We need to be benchmarking the __getitem__ methods, right?

[Edited!!]
OOPS! I didn't pull down the latest changes. These timings are for the version with checking length included.
The results with the latest commits are almost identical to the timings for main.

Yay!!

old post
import timeit
import networkx as nx

G = nx.binomial_graph(500, 0.3, seed=1234)

def bench(stmt, number=10):
    return timeit.timeit(stmt, number=number, globals=globals())

for GC in [nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph]:
    H = GC(G.edges)
    print(f"{H.__class__.__name__}:  for e in H.edges: H.edges[e]",
        bench("for e in H.edges: H.edges[e]"))

Results: on main

Graph:  for e in GG.edges: GG.edges[e] 0.06632070895284414
DiGraph:  for e in GG.edges: GG.edges[e] 0.04694624990224838
MultiGraph:  for e in GG.edges: GG.edges[e] 0.104632374830544
MultiDiGraph:  for e in GG.edges: GG.edges[e] 0.07047895807772875

Results on views_exceptions

Graph:  for e in GG.edges: GG.edges[e] 0.07536450028419495
DiGraph:  for e in GG.edges: GG.edges[e] 0.05708624981343746
MultiGraph:  for e in GG.edges: GG.edges[e] 0.11413858318701386
MultiDiGraph:  for e in GG.edges: GG.edges[e] 0.0762286246754229

@dschult

dschult commented Apr 12, 2026

Copy link
Copy Markdown
Member

Oops! My previous post had timings for the version of the PR with the length checks included.
When I pulled the new commits the timing difference between main and thr PR goes away. Yay!
(I've edited/updated that post)

So the remaining nit I have is a request to use raise instead of raise err. That way there aren't two exceptions being raised/handled. The raise err part doesn't appear as a separate exception in the traceback.

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Cell In[3], line 1
----> 1 G.edges[1, -1]

File ~/NX/NXdschult/networkx/classes/reportviews.py:1198, in OutEdgeView.__getitem__(self, e)
   1196 u, v = e
   1197 try:
-> 1198     return self._adjdict[u][v]
   1199 except KeyError as err:
   1200     err.add_note(f"The edge {e} is not in the graph")

KeyError: -1
The edge (1, -1) is not in the graph

vs the current PR branch error:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Cell In[3], line 1
----> 1 G.edges[1, 0, 42]

File ~/workplace/networkx/networkx/classes/reportviews.py:1479, in OutMultiEdgeView.__getitem__(self, e)
   1477 except KeyError as err:
   1478     err.add_note(f"The edge {e} is not in the graph")
-> 1479     raise err

File ~/workplace/networkx/networkx/classes/reportviews.py:1476, in OutMultiEdgeView.__getitem__(self, e)
   1474 u, v, k = e
   1475 try:
-> 1476     return self._adjdict[u][v][k]
   1477 except KeyError as err:
   1478     err.add_note(f"The edge {e} is not in the graph")

KeyError: 0
The edge (1, 0, 42) is not in the graph

@amcandio

Copy link
Copy Markdown
Contributor Author

Good point, fixed!

@dschult dschult left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @amcandio !!

This looks good to me!

@dschult
dschult merged commit 0580974 into networkx:main Apr 12, 2026
44 checks passed
@dschult dschult added this to the 3.7 milestone Apr 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Development

Successfully merging this pull request may close these issues.

3 participants