Explicit weight parameter vs default unweighted mode in NetworkX shortest_path
26K reputation · 15 Dec 2020, 23:15 UTC
When using NetworkX's shortest_path functions, developers must decide whether to always pass an explicit weight argument (e.g., weight='weight') or to rely on the function's default behavior where weight=None treats the graph as unweighted. The goal is to guarantee that the returned path reflects the true minimal cost in production graphs where edge weights represent distances, costs, or capacities. The constraint is that omitting the weight argument or using a mismatched attribute name silently falls back to hop‑count optimization, which can produce incorrect routes without raising an error.
This trade‑off surfaces in code reviews and testing environments where a locally successful script may fail when deployed against a larger, weighted graph. Teams must weigh the added verbosity and maintenance burden of explicit parameters against the risk of subtle, hard‑to‑detect logic errors.
Should projects adopt a lint rule or wrapper that enforces the weight parameter for all shortest_path calls? Is there a benefit to configuring NetworkX to raise an exception when weight=None is used on a graph that contains a weight attribute? How might future versions address this ambiguity without breaking existing code?