Skip to content

Making edge view behavior consistent across different graph types - #8533

Open
amcandio wants to merge 6 commits into
networkx:mainfrom
amcandio:consistent_views
Open

amcandio wants to merge 6 commits into
networkx:mainfrom
amcandio:consistent_views

Conversation

@amcandio

@amcandio amcandio commented Feb 23, 2026 •

Copy link
Copy Markdown
Contributor

This PR makes .edges views consistent when using __contains__ and __getitem__ and also makes exceptions clearer when an edge is not found.

contains vs getitem consistency

In multigraphs, contains accepts two elements but getitem doesnt:

>>> (0,1) in G.edges # nx.MultiDiGraph()
True

>>> G.edges[0,1] # nx.MultiDiGraph()
Traceback (most recent call last):
  File ~/amcandio/networkx/classes/reportviews.py:1470 in __getitem__
    u, v, k = e
ValueError: not enough values to unpack (expected 3, got 2)

Error messaging: KeyError

When accessing a missing edge

>>> G = nx.MultiDiGraph([(0, 1)])
>>> G.edges[1,0,0]
Traceback (most recent call last):
  File ~/amcandio/networkx/classes/reportviews.py:1471 in __getitem__
    return self._adjdict[u][v][k]
KeyError: 0

which can be confusing as it reads as the node is missing. It is also inconsistent with nx.Graph behavior:

>>> G=nx.Graph(nodes=[0, 1])
>>> G.edges[0,1]
Traceback (most recent call last):
  File ~/amcandio/networkx/classes/reportviews.py:1201 in __getitem__
    raise KeyError(f"The edge {e} is not in the graph.")
KeyError: 'The edge (0, 1) is not in the graph.'

Error messaging: tuple length mismatch

When passing the wrong amount of elements, sometimes we get a clear error, sometimes we don't. Simple graphs just return False when passing the wrong amount of elements while Multigraphs raise:

>>> (0,) in G.edges # nx.Graph()
False
>>> (1,1,1,1,1) in G.edges # nx.MultiDiGraph()
Traceback (most recent call last):
  File ~/amcandio/networkx/classes/reportviews.py:1458 in __contains__
    raise ValueError("MultiEdge must have length 2 or 3")
ValueError: MultiEdge must have length 2 or 3
>>> G.edges[0,] # nx.MultiDiGraph()
Traceback (most recent call last):
  File ~/amcandio/networkx/classes/reportviews.py:1470 in __getitem__
    u, v, k = e
ValueError: not enough values to unpack (expected 3, got 1)

After this PR

We have:

  • Clear and consistent KeyError when edge is missing
  • Consistent contains and getitem behavior for all edge views
  • Consistent ValueError behavior for all edge views when passing the wrong amount of edges
>>> import networkx as nx
>>> G=nx.MultiDiGraph([(0,1)])
>>> (0, 1) in G.edges
True
>>> G.edges[0,1]
{}
>>>  G.edges[1,0]
Traceback (most recent call last):
  File ~/amcandio/networkx/classes/reportviews.py:1203 in __getitem__
    raise KeyError(f"The edge {e} is not in the graph.")
KeyError: 'The edge (1, 0) is not in the graph.'

>>> (1,1,1,1,1) in G.edges
False

We achieve this naturally in the code by removing duplicated __contains__ and __getitem__ definitions. Each subclass only needs to define how to parse edges into the tuple used to access internal adjacency dictionary.

@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.

This is really nice!! Thanks for diving into the views.

The first main question: what should MG.edges[1, 2] return for a multigraph MG?

Currently it raises. Historically, we made 2-tuples work for MultiEdgeView.__contains__ to enable code that worked for Graph also work for MultiGraph. Is there a use-case for getting the edge data with code for Graph that now will "just work" for MultiGraph?

Using the default key of 0 could become a generic way of handling 2-tuple input to multiedge functions that want a edge tuple. That could be powerful -- or really confusing. So the flip side of this question is "should MultiGraph.__contains__ allow 2-tuples?" Maybe both contains and getitem should raise?

This Pr has interesting refactors of those methods no matter what the answers to those questions are.

I guess we should also make sure any performance hit isn't problematic -- and readability is important too. More on that in the comments below.

Overall my early impression is positive: Using edge-key 0 as a kind of default edge-key has merit. And interesting code changes include the general loop for indexing into chains of dict-of-dict structures, and the match statement for handling edge tuples.

Thanks @amcandio !!

Comment thread networkx/classes/reportviews.py Outdated
Comment on lines +1198 to +1204
ret = self._adjdict
for elem in self._edge_as_tuple(e):
try:
ret = ret[elem]
except KeyError:
raise KeyError(f"The edge {e} is not in the graph.")
return ret

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.

This bit of code is a cool extendable way of looping over various length chains of dict-of-dict-of...of-dict constructions with various lengths of tuples of keys. So a dododod can get the last d with a 3-tuple key. And the same code works for dodod with a 2-tuple key. !:)!

We only have two options (length 2 or 3 tuples) so hardcoding based off len(e) is fairly easy too and probably more performant. Can it be included in the _edge_as_tuple method which is the heart of this refactor of inheritance? Something like _get_edge(e) with the match statement including the self._adjdict call once it figures out if we have a 2 or 3 tuple.

I like the generality of the loop -- but there are the usual questions of performance and readability here.
Performance of the general code vs hardcoding the cases of 2 and 3 length tuples. For readability, we could use more specific names than ret and elem, maybe dod or dict_of_dicts for ret and next_key for elem. A pre-comment for the block could present the generality of this loop -- something like # get inner dict of a nested chain of dict_of_dicts.

The other questions of readability and performance revolve around the subclasses overwriting _edge_as_tuple instead of the dunder __getitem__. There is less code in _edge_as_tuple, but you have to know the context from __getitem__ to understand the impact of the smaller function. That's the usual trade-off in inherited class structures -- you need to understand the whole thing to understand the impact of changes. So this question is probably less important than the general loop vs hardcoding.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, I had the same concern with the for loop. I reworked it so it is length-based only. The only possible overhead could come from checking if the underlaying graph is a multigraph.

This led me to rework all methods based on three variables:

  • out_edge (boolean, class level)
  • self._graph.is_directed()
  • self._graph.is_multigraph()

With this approach subclasses end up being pretty dumb and we could even remove them. Methods end up having some extra if-else handling, but it is a pattern we see in other parts of NetworkX

Comment thread networkx/classes/reportviews.py Outdated
Comment on lines +1448 to +1452
match e:
case (u, v):
return u, v, 0
case (u, v, k):
return u, v, k

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'm still learning about match and when to use it over if/elif constructions. Neat stuff!
What exactly is match actually checking here:

    match e:
        case (u, v):

Does it check for a tuple of length 2? Or Is it any iterable of length 2? I think it is a tuple of length 2....
Which is fine for this code. But I wonder if there is a way for match to check for any iterable of length 2 like u, v = e does.

I'm guessing the old-style code for this match is essentially:

    if not isinstance(e, tuple):
        raise TypeError
    N = len(e)
    if N == 2:
        return (*e, 0)
    if N == 3:
        return e
    raise ValueError

Is that your understanding of what match is doing here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

In this case match statement matches a Sequence of length 2 (which includes only list, tuple and range types). As per docs:

Like unpacking assignments, tuple and list patterns have exactly the same meaning and actually match arbitrary sequences. An important exception is that they don’t match iterators or strings.

so it won't match any iterator like classic unpacking does.

g_edges.add((edge[0], edge[1]))
g_edges.add((edge[1], edge[0]))
assert g_edges == set(embedding.edges), (
assert g_edges == {edge for u, v in embedding.edges for edge in [(u, v), (v, u)]}, (

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This one was needed bc the embedding declares "is_directed" as False. So the edge views now correctly remove duplicated edges.

@amcandio

amcandio commented Mar 2, 2026

Copy link
Copy Markdown
Contributor Author

I ended up dropping the match statement and the for loop handling.

This is really nice!! Thanks for diving into the views.

The first main question: what should MG.edges[1, 2] return for a multigraph MG?

Currently it raises. Historically, we made 2-tuples work for MultiEdgeView.__contains__ to enable code that worked for Graph also work for MultiGraph. Is there a use-case for getting the edge data with code for Graph that now will "just work" for MultiGraph?

Aah, that is great context! My main reason for it to do it is that, if x in S, then S[x] should be accepted too. With this change, we also make accessor consistent between nx.Graph and nx.MultiGraph.

>>> G = nx.MultiGraph([(0, 1, {'ale':0})])
>>> G.edges[0, 1]
{'ale': 0}

>>> G =  nx.Graph([(0, 1, {'ale':0})])
>>> G.edges[0, 1]
{'ale': 0}

Using the default key of 0 could become a generic way of handling 2-tuple input to multiedge functions that want a edge tuple. That could be powerful -- or really confusing. So the flip side of this question is "should MultiGraph.__contains__ allow 2-tuples?" Maybe both contains and getitem should raise?

I don't have a strong preference to be honest. My main motivation was consistency. I do like the fact of having code working for both cases but it can be confusing to have the library arbitrarily an edge for you.

I wouldn't have the __contains__ raise to not change historical behavior. What about having __getitem__ return a dictionary of keys when only u, v is passed? This would make G.edges[u, v][k] == G.edges[u, v, k].

This Pr has interesting refactors of those methods no matter what the answers to those questions are.

I guess we should also make sure any performance hit isn't problematic -- and readability is important too. More on that in the comments below.

Overall my early impression is positive: Using edge-key 0 as a kind of default edge-key has merit. And interesting code changes include the general loop for indexing into chains of dict-of-dict structures, and the match statement for handling edge tuples.

Thanks @amcandio !!

Thanks! I did a new refactor that basically removes the need for the separate classes. All the definitions are based on the underlaying graph properties (is_directed, is_multigraph). It might be a bit verbose but it is a pattern we do follow in some part of the library. What do you think?

@amcandio

amcandio commented Mar 2, 2026 •

Copy link
Copy Markdown
Contributor Author

I thought more about other API options. Having backwards compatiblity in mind, I think options 2 or 3 are the best. If I were to pick an API from scratch, I like options 4 and 5.

Option 1 – Current behavior

(u, v) in G.edges sets k=0 implicitly; G.edges[u, v] raises.

  • Pros: No breaking changes.
  • Cons: Implicit default k=0 is invisible, inconsistent with getitem which can be confusing.

Option 2 – Both raise

(u, v) in G.edges returns False and G.edges[u, v] raises.

  • Pros: Consistent, clear, no hidden assumptions.
  • Cons: Breaks legacy code that expects (u, v) in G.edges to work for MultiGraphs. Less “just works” migration from Graph to MultiGraph.

Option 3 – Default k=0 for both (PR version)

(u, v) in G.edges and G.edges[u, v] both pick k=0.

  • Pros: Fully consistent between __contains__ and __getitem__. Works like default key behavior in MultiGraph edge addition.
  • Cons: Implicit key selection remains invisible. Still picks arbitrarily if multiple edges exist.

Option 4 – (u, v) in G.edges relaxed, G.edges[u, v] fails on multiple keys

(u, v) in G.edges meaning “any edge exists between u and v”.

G.edges[u, v] means returns edge data only if there’s a single edge, raises if multiple edges.

  • Pros: No hidden defaults, still allows some legacy code to work (easier for catching bugs).
  • Cons: More different types of behavior. It hiddenly breaks backwards compatibility, (u, v) in G.edges returning False might now return True.

Option 5 – (u, v) in G.edges relaxed, G.edges[u, v] returns dict of edges keyed by edge keys

(u, v) in G.edges means existence check as above. G.edges[u, v] returns {key: attr_dict} for all edges.

Basically G.edges[u, v, k] == G.edges[u, v][k].

  • Pros: Fully consistent, no hidden assumptions, explicit access to all edges.
  • Cons: Slightly different from Graph behavior (legacy code expecting a single dict breaks). Moreover, this might silently fail because G.edge[u, v] for Graph also returns a dict. It also hiddenly breaks backwards compatibility, (u, v) in G.edges returning False might now return True.

@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.

Thanks for diving into this @amcandio , this is quite interesting and super worthwhile!

I thought more about other API options.

At a high-level, I think the current behavior makes the most sense (almost!) --- at least from the perspective of their being a difference between __contains__ and __getitem__ for a multigraph. In my mental model, asking (0, 1) in MG (without specifying a key) is valid and should be true if any edge exists between nodes 0 and 1. Now in practice, it turns out that it's only true as long as the edge (0, 1, 0) is present. The "implicitly k=0" part of this is an unnecessary restriction IMV; I'd expect the following behavior:

>>> MG = nx.MultiGraph([(0, 1, 99)])  # edge key = 99
>>> (0, 1) in MG
True

__getitem__ is different because the user is asking about an edge attribute, which is tied to a specific edge - so enforcing the requirement that the user provide the edge key makes the most sense to me.

Option 3 (i.e. treat 0 as the default edge key for getitem) is an interesting idea, but personally I'm quite leery of it... it feels like a potential source for hard-to-find bugs. IME, a lot of the code surrounding dealing with multigraphs involves "condensing" multi edges to single value, (e.g. summing edge weights, taking the minimum edge weight, etc.) The danger of MG[0, 1]["attr"] returning the attribute for the key0 edge is that the author may be tempted to assume (or worse, not even realize) that they are getting the value they want (i.e. a minimum or maximum or sum of the multiedge attributes), when in fact they are getting an arbitrary multiedge value. The current pattern of raising an exception in this case prevents this footgun and forces explicitness on the user, and I think that's a good thing!

So my initial opinion on desired semantics tends toward option 1, though with the removal checking for edge key 0 and instead checking for any key.

@amcandio

amcandio commented Mar 3, 2026

Copy link
Copy Markdown
Contributor Author

I thought more about this. OutEdgeView inherits Set and Mapping (which I think it makes sense). Having x in G.edges being inconsistent with G.edges[x] can be confusing given that we expect this object to be a mapping.

I agree that setting k=0 behind the scenes can hide bugs and confuse users. The only remaining option in my option would be having getitem raise and contains return False. If we want to check if there is any edge between u and v, we can simply do u in G[v].

In summary, in my opinion MultiGraph.edges is a mapping from (u, v, k) to data, therefore (u, v) is not a key.

@rossbar

rossbar commented Mar 3, 2026

Copy link
Copy Markdown
Contributor

In summary, in my opinion MultiGraph.edges is a mapping from (u, v, k) to data, therefore (u, v) is not a key.

I agree that this is the most correct interpretation based on definitions, but I don't think it's the correct approach now given the existing behavior. In practice, (u, v) in MG.edges "just works" for nearly every case (i.e. every case where the key0 edge exists, which will always be true unless the user explicitly passed in keys for the edges). I'm personally reticent to break this behavior (a "practicality beats purity" argument, largely!).

@dschult

dschult commented Mar 4, 2026

Copy link
Copy Markdown
Member

If we want to check if there is any edge between u and v, we can simply do u in G[v].

This reasoning is a slippery slope to getting rid of G.edges altogether. Everything G.edges does can be done pretty easily using G._adj[u][v][k] and G._pred[u][v][k]. The trickiest parts for users (including developers of algorithms) is ensuring only one direction reported for undirected case, and writing code that works for both multigraphs and simple graphs.

We do already have a method G.has_edge that checks for an edge -- but that hasn't really "caught on" as far as I can tell.

In summary, in my opinion MultiGraph.edges is a mapping from (u, v, k) to data, therefore (u, v) is not a key.

It feels like this PR was started due to inconsistency between __contains__ and __geitem__. Did that arise from a use-case where it was confusing? That is much more convincing to me than a type-bsaed argument that it is like a mapping so should behave like a mapping.

I think describing MultiGraph.edges as a mapping is limiting. It has some mapping aspects. It has some set aspects. And it tries to make it easy to write code that works for all 4 graph classes. It doesn't do the latter goal completely, but it is pretty good. Whenever things get complicated it is often better to go back to the adjacency approach G[u][v][k]. I guess that points out a 4th goal: It allows people to think about the graph object as a collection of nodes and edges instead of nodes and adjacencies.

One aspect that we currently fail on for making code easy to write for all 4 classes is G.edges(keys=True/False) which doesn't work for non-multi graphs. The refactor of this PR does provide this... It's not clear whether using keys=True for Graph/DiGraph should raise or ignore or return the key as 0, or whether it makes the simple graph api too complicated.

Does having a keys kwarg for Graph.edges, along with a concept that each simple graph edge has an implicit key=0, help us solve provide a nicer way to write code that works for all 4 classes?

If we can find a way to make it easier to write code for all four cases, that could be a motivation for a possibly backward breaking change in NX 4.0. We are getting close to double digit minor release numbers after-all. :) But we need to make a case for improved interface leading to simplification of algorithm code. What's a part of NetworkX where the code is pretty ugly due to handling edges keys with the edges attribute?

@amcandio

Copy link
Copy Markdown
Contributor Author

It feels like this PR was started due to inconsistency between contains and geitem. Did that arise from a use-case where it was confusing?

Not exactly, that is just a surprise I found when reading the code. This is what originated my use-case #8588.

Does having a keys kwarg for Graph.edges, along with a concept that each simple graph edge has an implicit key=0, help us solve provide a nicer way to write code that works for all 4 classes?

I like this. I think it makes sense to spend efforts on making NX easier to write code that works for both multi and simple graphs (I'd appreciate it as a user myself!).

@rossbar

rossbar commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

After the discussions we had at the last summit which highlighted how disruptive behavior changes can be for downstream code, I'm even more -1 on any changes that would result in any backward incompatible behavior for the core data structures.

The discussion here is very valuable, and there are some good ideas but I don't think the current implementation will move forward. Should we close and open separate PRs for some of the individual discussion points? WDYT @amcandio ?

This branch has not been deployed

No deployments
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