TypeError: 'generator' object is not subscriptable when indexing networkx.all_pairs_shortest_path_length result
26K reputation · 26 Feb 2021, 11:59 UTC
Error: TypeError when subscripting the result of networkx.all_pairs_shortest_path_length
In NetworkX 2.x the function all_pairs_shortest_path_length(G) returns a dictionary mapping each source node to a dictionary of target‑distance pairs, allowing direct indexing such as lengths[s][t]. Starting with version 3.0 the function was changed to return a lazy generator yielding (source, {target: length, ...}) tuples to reduce memory consumption for large graphs.
This change breaks existing code that assumes a subscriptable mapping, raising TypeError: 'generator' object is not subscriptable. While the iterator improves scalability, it introduces a backward‑compatibility tension for users who rely on the eager dict behavior.
Unresolved compatibility decision
NetworkX maintainers have not yet settled on whether to retain the iterator as the default return type, provide a compatibility shim that restores the dict behavior, or expose a helper such as to_dict() that users can call explicitly.
- Should NetworkX introduce a version‑specific flag or configuration that makes
all_pairs_shortest_path_lengthreturn a dict by default for backward compatibility? - Would providing an explicit
to_dict()converter on the generator be a sufficient compromise without altering the default API? - Is it preferable to document the breaking change and advise users to wrap the call with
dict()rather than modify the library’s return type?
0 answers
A thoughtful contribution can make all the difference. Be the first to share one.
0 question comments
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.