Repository navigation
Conversation
dschult
left a comment
There was a problem hiding this comment.
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 !!
| 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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
| match e: | ||
| case (u, v): | ||
| return u, v, 0 | ||
| case (u, v, k): | ||
| return u, v, k |
There was a problem hiding this comment.
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 ValueErrorIs that your understanding of what match is doing here?
There was a problem hiding this comment.
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)]}, ( |
There was a problem hiding this comment.
This one was needed bc the embedding declares "is_directed" as False. So the edge views now correctly remove duplicated edges.
|
I ended up dropping the match statement and the for loop handling.
Aah, that is great context! My main reason for it to do it is that, if
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
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? |
|
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
Option 2 – Both raise
Option 3 – Default k=0 for both (PR version)
Option 4 – (u, v) in G.edges relaxed, G.edges[u, v] fails on multiple keys
Option 5 – (u, v) in G.edges relaxed, G.edges[u, v] returns dict of edges keyed by edge keys
Basically G.edges[u, v, k] == G.edges[u, v][k].
|
rossbar
left a comment
There was a problem hiding this comment.
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.
|
I thought more about this. 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 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, |
This reasoning is a slippery slope to getting rid of We do already have a method
It feels like this PR was started due to inconsistency between 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 One aspect that we currently fail on for making code easy to write for all 4 classes is Does having a 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 |
Not exactly, that is just a surprise I found when reading the code. This is what originated my use-case #8588.
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!). |
|
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 PR makes
.edgesviews 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:
Error messaging: KeyError
When accessing a missing edge
which can be confusing as it reads as the node is missing. It is also inconsistent with
nx.Graphbehavior: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:
After this PR
We have:
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.