Python graph libraryRust core0.4.1 on PyPI
NetworkX, rebuilt in Rust, tie-breaks and all.
FrankenNetworkX is a Rust port of NetworkX that you install from PyPI and switch on with one line. The NetworkX calls you already make run on native kernels and return what NetworkX returns: the same values in the same order, the same exceptions, the same error messages.
Run it on this graph
—ms in Rust, in this tab
Loading FrankenNetworkX…
Click or tap two nodes to route between them. Every answer comes from FrankenNetworkX's own Rust crates, compiled to a 358 KB WebAssembly module; the Python wheels are built from the same crates.
- 6,815NetworkX tests passNetworkX 3.6.1's own suite with FrankenNetworkX as the backend. None fail.
- 4,129/4,129public paths presentEvery import and signature in NetworkX 3.6.1, with the same shape.
- 1.3–194×faster kernelsTimed against NetworkX in one process. Whole jobs: 1.1–2.2×.
- 400/400tie-breaks matchedShuffled edge orders, same route as NetworkX. Try it here.
- 12algorithms with receiptsEach hashes its tie-break decisions into a Blake3 fingerprint.
Switch
Turn it on with one line.
Install the wheel and tell NetworkX to prefer it. Calls FrankenNetworkX supports run in Rust, and everything else falls through to NetworkX unchanged. Nothing in your code has to know which library answered.
Two ways in
As a backend, or as the module itself.
As a backend, NetworkX's own dispatcher hands supported calls to FrankenNetworkX and converts the results back. Imported directly, it is a NetworkX-shaped module whose graphs are Rust from the start.
Backend protocol, in the guidePick how you want to switch.
Worked exampleimport networkx as nx
nx.config.backend_priority = ["franken_networkx"]
G = nx.read_edgelist("collaborations.txt")
nx.pagerank(G) # runs in FrankenNetworkX
nx.connected_components(G) # so does thisNothing else in your code changes. NetworkX converts your graph once and keeps the copy in its cache, so repeated calls on the same graph skip the conversion.
import franken_networkx as fnx
G = fnx.Graph()
G.add_weighted_edges_from([("a", "b", 3.0), ("b", "c", 1.5), ("a", "c", 10.0)])
fnx.shortest_path(G, "a", "c", weight="weight") # ['a', 'b', 'c']
fnx.pagerank(G)The graph lives in Rust from the start, so no call pays for a conversion. Every NetworkX 3.6.1 import path exists under the same name.
import networkx as nx
G = nx.karate_club_graph()
nx.betweenness_centrality(G, backend="franken_networkx")Useful for an A/B check. An explicit backend raises NotImplementedError if FrankenNetworkX doesn't register the function, where backend_priority would fall back.
# tests/conftest.py
import networkx as nx
import franken_networkx # registers the backend
nx.config.backend_priority = ["franken_networkx"]Run your existing tests through it. A failure is either a FrankenNetworkX bug worth reporting or a documented divergence your code relied on.
Dispatch
What NetworkX does with each call.
NetworkX checks whether a backend implements a function before sending a call to it. 421 functions are registered in the 0.4.1 release (476 on main). The rest run in NetworkX exactly as before. These are NetworkX's own debug logs, recorded with networkx 3.6.1 and franken-networkx 0.4.1.
Pick a call and read what the dispatcher logged.
Recorded outputnetworkx DEBUG log
- asks
Call to 'shortest_path' has inputs from {'networkx'} backends, and will try to use backends in the following order: ['franken_networkx', 'networkx'] - converts
Converting input graphs from 'networkx' backend to 'franken_networkx' backend for call to 'shortest_path' - converts
Caching converted graph (from 'networkx' to 'franken_networkx' backend) in call to 'shortest_path' for 'G' argument - Rust side
Using backend 'franken_networkx' for call to 'shortest_path' with arguments: (G=Graph(nodes=2000, edges=5991), source=0, target=1999, weight='weight', method='dijkstra')
The first call converts the NetworkX graph and caches the copy on G. FrankenNetworkX answers.
networkx DEBUG log
- asks
Call to 'pagerank' has inputs from {'networkx'} backends, and will try to use backends in the following order: ['franken_networkx', 'networkx'] - converts
Converting input graphs from 'networkx' backend to 'franken_networkx' backend for call to 'pagerank' - cache hit
Using cached converted graph (from 'networkx' to 'franken_networkx' backend) in call to 'pagerank' for 'G' argument - Rust side
Using backend 'franken_networkx' for call to 'pagerank' with arguments: (G=Graph(nodes=2000, edges=5991), alpha=0.85, personalization=None, max_iter=100, tol=1e-06, nstart=None, weight='weight', dangling=None)
The second call finds the converted graph in the cache, so it skips the conversion.
networkx DEBUG log
- asks
Call to 'connected_components' has inputs from {'networkx'} backends, and will try to use backends in the following order: ['franken_networkx', 'networkx'] - converts
Converting input graphs from 'networkx' backend to 'franken_networkx' backend for call to 'connected_components' - cache hit
Using cached converted graph (from 'networkx' to 'franken_networkx' backend) in call to 'connected_components' for 'G' argument - Rust side
Using backend 'franken_networkx' for call to 'connected_components' with arguments: (G=Graph(nodes=2000, edges=5991))
Same graph, same cache. Each call costs only the algorithm and the result's trip back.
networkx DEBUG log
- asks
Call to 'betweenness_centrality' has inputs from {'networkx'} backends, and will try to use backends in the following order: ['franken_networkx', 'networkx'] - converts
Converting input graphs from 'networkx' backend to 'franken_networkx' backend for call to 'betweenness_centrality' - cache hit
Using cached converted graph (from 'networkx' to 'franken_networkx' backend) in call to 'betweenness_centrality' for 'G' argument - Rust side
Using backend 'franken_networkx' for call to 'betweenness_centrality' with arguments: (G=Graph(nodes=2000, edges=5991), k=200, normalized=True, weight=None, endpoints=False, seed=<random.Random object>)
Sampled betweenness with seed 7: FrankenNetworkX returns exactly NetworkX's answer, every score equal. This script checks that each time it runs.
networkx DEBUG log
- asks
Call to 'estrada_index' has inputs from {'networkx'} backends, and will try to use backends in the following order: ['franken_networkx', 'networkx'] - falls back
Backend 'franken_networkx' does not implement 'estrada_index' - falls back
Trying next backend: 'networkx' - asks
Call to 'subgraph_centrality' has inputs from {'networkx'} backends, and will try to use backends in the following order: ['franken_networkx', 'networkx'] - falls back
Backend 'franken_networkx' does not implement 'subgraph_centrality' - falls back
Trying next backend: 'networkx' - asks
Call to 'to_numpy_array' has inputs from {'networkx'} backends, and will try to use backends in the following order: ['franken_networkx', 'networkx'] - converts
Converting input graphs from 'networkx' backend to 'franken_networkx' backend for call to 'to_numpy_array' - converts
Caching converted graph (from 'networkx' to 'franken_networkx' backend) in call to 'to_numpy_array' for 'G' argument - Rust side
Using backend 'franken_networkx' for call to 'to_numpy_array' with arguments: (G=Graph(name='Zachary's Karate Club', nodes=34, edges=78), nodelist=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33], dtype=None, order=None, multigraph_weight=<built-in function sum>, weight='weight', nonedge=0.0)
FrankenNetworkX does not register estrada_index, so NetworkX runs it. Inside, NetworkX calls to_numpy_array, which is registered, so that one step goes to FrankenNetworkX.
networkx DEBUG log
- silent
(nothing logged: NetworkX ran it itself)
Functions that change their input are not sent to a backend under backend_priority. NetworkX relabels your graph in place.
logging.getLogger("networkx").setLevel(logging.DEBUG). Converting a NetworkX graph costs about 0.66 µs per edge, and NetworkX's cache pays it once per graph. With the cache off, cheap kernels lose to plain NetworkX; see where it's slower.Same answers
NetworkX's answer, in NetworkX's order.
Many graph questions have more than one right answer, and NetworkX picks one by the order you built the graph in. Code downstream comes to depend on that pick. FrankenNetworkX makes the same pick, and treats iteration order, return types, exceptions and error text as part of the API.
Tie-breaks
Six equal routes. NetworkX's pick every time.
On a 3×3 grid every corner-to-corner route takes four steps. Which one Dijkstra returns depends on the order the edges went in, because NetworkX's heap pops equal distances first in, first out. Shuffle the order, and the Rust kernel running in this page returns the route NetworkX returned for that same order.
Shuffle the order the twelve edges are added in.
InteractiveEdge ordera–b first, then a–d, …
NetworkX 3.6.1recorded in CPython 3.13.9
—
FrankenNetworkXRust kernel, running here
—
Loading the engine…
A port that breaks ties by namefor contrast, computed in JavaScript
—
A port that iterates a hash mapfor contrast, a fresh hash seed each run
—
0 of 0 orders: FrankenNetworkX agrees
0 of 0: the by-name port agrees
0 of 0: the hash-map port agrees
Parity, live
16 answers, checked in your browser.
Zachary's karate club (34 people, 78 weighted friendships) is the graph NetworkX ships for examples. Each row runs one of FrankenNetworkX's Rust kernels here and compares its answer with the one NetworkX gave in CPython, in order wherever NetworkX's answer has one.
Run the battery and read each verdict.
InteractiveEach row builds the karate graph in Rust, runs one kernel and compares the answer with NetworkX's.
| NetworkX call | Compared on | Verdict | What came back | Kernel |
|---|---|---|---|---|
shortest_path(G, "16", "25", weight="weight") | Same path, node for node | waiting | — | — |
single_source_dijkstra(G, "0") | Same distances, in the order Dijkstra settles them | waiting | — | — |
bfs_edges(G, "0") | Same tree edges, in the same order | waiting | — | — |
bfs_layers(G, "0") | Same layers, same order within each | waiting | — | — |
connected_components(G) | Same groups of nodes | waiting | — | — |
betweenness_centrality(G) | Same scores, same node order | waiting | — | — |
closeness_centrality(G) | Same scores, same node order | waiting | — | — |
clustering(G) | Same coefficients, same node order | waiting | — | — |
pagerank(G, weight=None) | Same ranks to within the solver tolerance | waiting | — | — |
triangles(G) | Same counts, same node order | waiting | — | — |
core_number(G) | Same cores, same node order | waiting | — | — |
louvain_communities(G, seed=7) | Same communities for the same seed | waiting | — | — |
minimum_spanning_tree(G) | Same tree edges and total weight | waiting | — | — |
articulation_points(G) | Same nodes, same order | waiting | — | — |
bridges(G) | Same edges, same order | waiting | — | — |
max_weight_matching(G) | Same pairs | waiting | — | — |
The contract
Same types, same errors, same words.
Code that catches NetworkXNoPath and reads its message, or consumes a generator lazily, keeps working. These outputs were recorded from networkx 3.6.1 and franken-networkx 0.4.1 on Python 3.13.9, running the same lines with nx bound to each.
Pick a snippet and compare the two outputs.
Recorded outputG = nx.Graph([("a", "b")])
G.add_node("z")
nx.shortest_path(G, "a", "z")import networkx as nx
NetworkXNoPath: No path between a and z.
import franken_networkx as nx
NetworkXNoPath: No path between a and z.
identicalSame exception class, same message. Code that catches NetworkXNoPath and reads str(e) keeps working.
G = nx.Graph([("a", "b")])
nx.shortest_path(G, "a", "q")import networkx as nx
NodeNotFound: Target q is not in G
import franken_networkx as nx
NodeNotFound: Target q is not in G
identicalNodeNotFound is not a NetworkXError subclass in NetworkX, and it is not one here either.
D = nx.DiGraph([(1, 2), (2, 3), (3, 1)])
list(nx.topological_sort(D))import networkx as nx
NetworkXUnfeasible: Graph contains a cycle or graph changed during iteration
import franken_networkx as nx
NetworkXUnfeasible: Graph contains a cycle or graph changed during iteration
identicaltopological_sort is a generator, so the error arrives when it is consumed, as in NetworkX.
G = nx.cycle_graph(4)
paths = nx.all_shortest_paths(G, 0, 2)
type(paths).__name__, list(paths)import networkx as nx
('generator', [[0, 1, 2], [0, 3, 2]])import franken_networkx as nx
('generator', [[0, 1, 2], [0, 3, 2]])identicalA generator stays a generator. Nothing is collected into a list behind your back.
G = nx.Graph()
G.add_edges_from([("c", "a"), ("b", "c"), ("a", "b")])
list(G.nodes), list(G.edges), list(G["c"])import networkx as nx
(['c', 'a', 'b'], [('c', 'a'), ('c', 'b'), ('a', 'b')], ['a', 'b'])import franken_networkx as nx
(['c', 'a', 'b'], [('c', 'a'), ('c', 'b'), ('a', 'b')], ['a', 'b'])identicalNodes, edges and adjacency iterate in the order you built the graph.
G = nx.Graph([(5, 6), (1, 2), (3, 4), (6, 7)])
[sorted(c) for c in nx.connected_components(G)]import networkx as nx
[[5, 6, 7], [1, 2], [3, 4]]
import franken_networkx as nx
[[5, 6, 7], [1, 2], [3, 4]]
identicalComponents come out in the order NetworkX finds them, not sorted and not hashed.
G = nx.Graph()
G.add_weighted_edges_from([("a", "n", 1), ("n", "z", 1), ("a", "m", 1), ("m", "z", 1)])
nx.dijkstra_path(G, "a", "z")import networkx as nx
['a', 'n', 'z']
import franken_networkx as nx
['a', 'n', 'z']
identicalTwo routes cost 2. NetworkX's heap pops equal distances first in, first out; so does this.
t = ("a", 1)
G = nx.Graph()
G.add_node(t)
next(iter(G)) is timport networkx as nx
True
import franken_networkx as nx
True
identicalThe node you get back is the object you put in, not a copy rebuilt from a string.
M = nx.MultiGraph()
for k in (0, 0.0, False):
M.add_edge(1, 2, key=k)
M.number_of_edges()import networkx as nx
1
import franken_networkx as nx
1
identical0, 0.0 and False are one dict key in Python, so they name one parallel edge.
The evidence
NetworkX's own tests, run against it.
The strictest check is the one NetworkX wrote for itself. Its suite runs with FrankenNetworkX as the backend on every quality run, held to a ratchet that fails the run on any new failure.
- 6,815NetworkX's own tests pass
NetworkX 3.6.1's test suite with FrankenNetworkX as the backend: 0 failures, 0 errors (2026-09-24). Plain NetworkX passes 6,816; with the backend, 80 tests are skipped instead of 78.
ratchet_v1.json - 4,129 / 4,129public paths present
Every import and signature in NetworkX 3.6.1's public surface exists with the same shape: 0 partial, 0 missing, 796 excluded with a stated reason. Drift fails the quality run.
docs/coverage.md - 68,318parity tests passed
Call-by-call comparisons with NetworkX across 1,101 test files, 0 failed (2026-09-24). They check values, iteration order, exception classes and message wording.
run_python_parity_suite.py - 33fuzz targets
Parsers and algorithm families under cargo-fuzz. Every quality run replays the saved corpora and fuzzes each target for 10 seconds (4.76 million executions on 2026-09-24, no failures).
fuzz/fuzz_targets
Speed
Native kernels, timed against NetworkX.
In the project's gated benchmarks, graph kernels run 1.3× to 194× faster than NetworkX 3.6.1, and whole jobs from loading a file to writing results finish 1.1× to 2.2× sooner. Some single operations on the graph object are slower, and this chapter lists those too.
Kernels
Faster where the work is.
Each bar is NetworkX's time divided by FrankenNetworkX's for the same call on the same graph, after both outputs were checked to be identical. The scale is logarithmic. Workloads differ from row to row; the note on each bar says what was measured.
Filter by family, then show the losses too.
MeasuredWhole jobs
File to result, 1.1× to 2.2× sooner.
Each of these five jobs loads a slice of a real co-authorship network (SNAP's Astro Physics collaboration graph), cleans it, analyses it and writes the result, so the ratio includes parsing, conversion and output as well as the kernels.
Read across a row to see how each job scales.
Measured| Job | 1,000 nodes13,410 edges | 5,000 nodes77,598 edges | 10,000 nodes143,680 edges |
|---|---|---|---|
| Collaboration cohesionload → components and cores → cohort subgraph → export | 1.49×33% less time | 1.32×24% less time | 1.20×17% less time |
| Hub routingload → hub rank → shortest paths and BFS tree → radius-2 subgraph → export | 1.55×35% less time | 1.19×16% less time | 1.22×18% less time |
| Rich-club analysisload → rich club and onion layers → leader subgraph → export | 2.18×54% less time | 1.86×46% less time | 1.84×46% less time |
| Link recommendationsload → core rank → Jaccard and preferential scores → export | 1.10×9% less time | no stable differencethe gate could not separate them | 1.24×19% less time |
| Community detectionload → label propagation → largest community → assignments and export | 1.65×40% less time | 1.36×27% less time | 1.43×30% less time |
PYTHONHASHSEED=0 python3 scripts/perf_harness.py realistic-workloads.Method
How a number gets on this page.
Every ratio in this chapter passed the same gate. The README keeps its retractions too: a figure that later failed a corrected harness stays on the page, marked withdrawn.
- 01One process, both libraries
NetworkX 3.6.1 and FrankenNetworkX run in the same Python process, in alternating order, for 21 or more rounds.
- 02Outputs first
Before anything is timed, the complete outputs of the two are compared byte for byte. A row whose outputs differ is not timed.
- 03A/A nulls
Each library is also timed against itself. If either null drifts more than 2% from 1.0, the run is thrown out.
- 04Confidence, with margin
The verdict comes from a bootstrap confidence interval on the median ratio, with a 2× margin in log space. A row that can't clear it is published as undecidable.
- 05A quiet machine
Every CPU must stay under 20% busy before and during timing. A harness that can't prove that doesn't produce a number.
Where it's slower
Per-call costs it still pays.
A single operation on the graph object crosses from Python into Rust, and that crossing costs more than a Python dict lookup. Analytics win; tiny lookups in a tight loop can lose. These are the measured losses and their causes, each tracked as open work.
Know these before you benchmark a hot loop.
Measured| Operation | FrankenNetworkX vs NetworkX | Why |
|---|---|---|
G.adj | 0.90× | Descriptor access from Python. The README marks this figure stale, awaiting a fresh measurement. |
read_gml | 0.92× | The GML parse path. |
louvain_communities, weighted | 0.92× | Weighted input takes a slower route than the native kernel. |
n in G, absent key | 0.88× | A miss pays a set probe, then the canonical key path. |
preferential_attachment | 0.86× | Per-call boundary cost; NetworkX's work per pair is two degree lookups. |
read_multiline_adjlist | 0.80× | The parser is not native. |
G.add_edge(u, v, weight=w) | 0.66–0.71× | Each call converts its keyword dict into the native attribute map. |
G.has_node(n), absent key | 0.66× | A miss falls through to rebuilding the canonical key. |
MultiGraph.get_edge_data(u, v) | 0.57–0.62× | A registry lookup per call where NetworkX does two dict lookups. |
MultiGraph G[u][v] | 0.42–0.50× | Stacked Python view layers per subscript. |
MultiDiGraph.remove_node | 0.32–0.51× | A String-keyed store that frees about seven blocks per incident edge. |
Memory, attributed graphs | 3.4× NetworkX's RSS | Edge attributes are stored twice, natively and as the Python dict you see. Unattributed graphs use 0.63× NetworkX's memory. |
copy.copy(G), 10,000 nodes | 0.0031× | FrankenNetworkX copies the structure where NetworkX's shallow copy aliases it. |
Backend mode, conversion cache off | 0.026–0.40× | Every call converts the NetworkX graph first. With NetworkX's default cache on, the same calls win 1.7–17×. |
Graph.remove_node, 1,600 nodes | 0.52× | A flat 2.5–3.5 µs per call. It wins 1.75× at 25,600 nodes, where NetworkX's removal grows. |
Receipts
Every tie-break, on the record.
Twelve reference algorithms hash each tie-break decision they make into a Blake3 fingerprint, count their operations, and check that count against a closed-form bound. The same graph built in the same order gives the same fingerprint on any machine. A different fingerprint means the algorithm took a different path.
Witness, live
Run it twice. Same hash.
Pick an algorithm and a seeded random graph. The graph comes from FrankenNetworkX's own generator, which draws exactly the edges NetworkX draws for that seed. Run again and the fingerprint repeats. Shuffle the order the edges went in and it changes, because the algorithm met its ties in a different order.
Run it again, then shuffle the edge order.
InteractiveAlgorithm
Graph
ComplexityWitness—
- policy
- —
- dominant term
- —
- n, m
- —
- operations
- —
decision_path_blake3—
The registry
Twelve algorithms, each with a pinned policy.
The policy names the rule each reference kernel uses when several choices are equally good. Dijkstra's is NetworkX's own: equal-distance entries pop in the order they were pushed, because NetworkX's heap carries a counter as its second key. The registry describes these twelve reference kernels; the README notes where a public sibling, such as Prim, orders its ties differently.
| Reference algorithm | Family | Tie-break policy | Bound |
|---|---|---|---|
dijkstra | shortest_path | weight_then_insertion_orderLightest first; equal weights in the order they were pushed, as NetworkX's heap counter does. | O(n + m·log n) |
bellman_ford | shortest_path | insertion_orderNeighbours in the order the edges were added. | O(n·m) |
bfs | traversal | insertion_orderNeighbours in the order the edges were added. | O(n + m) |
dfs | traversal | insertion_orderNeighbours in the order the edges were added. | O(n + m) |
max_weight_matching | matching | weight_then_lexLightest first; equal weights by the smaller label. | O(n·m·α(n, m)) |
min_weight_matching | matching | weight_then_lexLightest first; equal weights by the smaller label. | O(n·m·α(n, m)) |
connected_components | connectivity | lex_minThe smallest label first. | O(n + m) |
strongly_connected_components | connectivity | insertion_orderNeighbours in the order the edges were added. | O(n + m) |
kruskal | trees | weight_then_lexLightest first; equal weights by the smaller label. | O(m·log m) |
prim | trees | weight_then_lexLightest first; equal weights by the smaller label. | O(m·log n) |
eulerian_circuit | euler | insertion_orderNeighbours in the order the edges were added. | O(m) |
topological_sort | dag | insertion_orderNeighbours in the order the edges were added. | O(n + m) |
Safety
Bad input fails closed.
Graphs often arrive from places you don't control. In strict mode FrankenNetworkX refuses malformed input and says exactly what was wrong. In hardened mode it repairs what it can within fixed limits and writes a decision record for every repair. Neither mode guesses silently.
Two policies
The same file, two answers.
These are FrankenNetworkX's GraphML and GML readers, compiled to WebAssembly. Pick a damaged file, then switch modes. Edit the text to try your own.
Pick a damaged file, then switch modes.
InteractiveA file
Mode
Result
Loading the reader…
Decision records
The decision rule
Allow, validate or refuse, by expected loss.
Graph operations are admitted by a small decision rule in fnx-runtime: given an estimated probability p that an operation is incompatible, take the action with the lowest expected loss. A plain add_edge enters at p = 0.08, a self-loop at 0.22. Hardened mode prices every mistake higher.
Slide p and watch the cheapest action change.
InteractiveLowest expected loss
allow
Allowing costs p × 100 = 8. Validating costs 25. Refusing costs (1 − p) × 60 = 55.2.
RuntimePolicy::action_for in crates/fnx-runtime: strict prices a wrong allow at 100, validation at 25 and a wrong refusal at 60; hardened at 120, 30 and 70. An unknown incompatible feature, or a p that isn't a number, refuses outright.Hardening
Built for input you didn't write.
- No unsafe code
#![forbid(unsafe_code)]in every crate of the workspace. - 33 fuzz targets
Parsers and algorithm families under cargo-fuzz, with corpora replayed and 10 seconds of fresh fuzzing on every quality run. Treat the parsers as fuzz-exercised, not proven, and still set your own limits for a public service.
- Typed attributes
Values come in as a closed set of types. GraphML booleans accept only the forms the format allows, so
0/1never turns into an integer downstream. - NaN and infinity
Non-finite weights go down NetworkX-exact paths, in every mode, so NaN behaves as it does in NetworkX.
- Bounded generators
In hardened mode, generator sizes are clamped (100,000 nodes; 20,000 for G(n, p) models) with a warning naming the clamp. Strict mode builds every size NetworkX builds.
- No unbounded recursion
Traversal-heavy algorithms (DFS, planarity, transitive closure) avoid unbounded recursion, so a very long path can't overflow the stack.
Inside
Twelve crates, one contract.
A call enters through a Python wrapper, crosses into Rust through PyO3 with the GIL released, runs on an insertion-ordered graph, and comes back as the Python type NetworkX would have returned.
One call
connected_components, down and back.
Six steps from your call to a Python set, through two Python layers and two Rust crates. The GIL is released at 826 call sites in the bindings, so other Python threads keep running while a kernel works.
Step through one call.
Worked examplefnx.connected_components(G), or nx.connected_components(G) with the backend switched on. In backend mode NetworkX first converts G (once, if its cache is on).
It validates the arguments with NetworkX's exceptions and wording. A call shape the native path doesn't take, such as a user callable, goes to an exact NetworkX-compatible route instead.
The binding borrows the Rust graph inside the Python object, so nothing is copied, and releases the GIL. Other Python threads keep running.
It works on dense node indices taken from the insertion-ordered adjacency, so it meets nodes in NetworkX's order. Reference kernels record each tie-break into a witness.
With the GIL back, each component goes out as a Python set straight from Rust, in the order Rust found it. No intermediate list.
A generator stays a generator. For the 24 wrapper-patched functions listed in docs/raw_vs_public_audit.md, the wrapper fixes up ordering here.
Storage
Insertion order is the index.
The adjacency is built so that matching NetworkX's iteration order costs nothing: nodes get slots in the order they arrive, and every neighbour row is appended in order.
Memory model, in the guidepub struct Graph {
node_order: FxIndexMap<String, usize>, // name → slot, in insertion order
slot_names: Vec<Option<String>>, // slot → name; None once removed
adj_indices: Vec<Vec<usize>>, // slot → neighbour slots, in insertion order
edges: FxIndexMap<(usize, usize), AttrMap>, // (min, max) slot pair → attributes
// plus revision-keyed caches
}- Insertion order is the index. Iteration follows the order you built the graph, which is how NetworkX's dicts behave, with no sorting step.
- Adjacency and attributes live apart. Walking neighbours never touches attribute payloads; setting a weight never disturbs neighbour order.
- Two tiers of attributes. Kernels read a typed native copy; your code reads real Python dicts, so
G.edges[u, v]returns the objects you stored. - The memory cost, stated. Without attributes a graph takes 0.63× NetworkX's memory. With one attribute per edge it takes 3.4×, because attributes are stored twice. A single store is on the roadmap.
The crates
Twelve crates, each with one job.
All twelve are published on crates.io at 0.4.1, so Rust code can use the graph classes and kernels without Python.
fnx-classesGraph, DiGraph, MultiGraph, MultiDiGraphInsertion-ordered slot storage; a removal tombstones a slot instead of renumbering.
fnx-algorithmsThe algorithms106,504 lines with inline tests; 687 public functions.
fnx-cgseCanonical Graph Semantics Engine13 tie-break policies, complexity witnesses, Blake3 decision-path hashes.
fnx-runtimeStrict and hardened modesThe decision rule, decision records and the evidence ledger.
fnx-pythonPyO3 bindingsOne ABI3 wheel for Python 3.10 and up. Releases the GIL at 826 call sites.
fnx-generatorsGraph generatorsSeeded through a port of CPython's random module, the Mersenne Twister NetworkX's seeds drive.
fnx-readwriteFile formatsEdge list, adjacency list, GraphML, GML, node-link JSON, Pajek, GEXF.
fnx-viewsViewsBorrowed snapshots and revision-tracked cached views.
fnx-convertConversionsDict-of-dicts, dict-of-lists, NumPy, SciPy and pandas round trips.
fnx-dispatchDispatchBackend registry and fail-closed routing.
fnx-conformanceDifferential harnessReplays fixtures against the NetworkX oracle and writes structured reports.
fnx-durabilityRaptorQ sidecarsErasure-coded copies of long-lived evidence, with scrub and decode proofs.
Version 0.4.1, Python 3.10 and up
Get started.
Three lines from here to your existing code running on Rust kernels. If a result ever differs from NetworkX and the difference isn't documented, that's a bug: file it with a snippet that calls both.
Step 1
Install
Prebuilt wheels for Linux (x86_64, aarch64, musl), macOS (Intel and Apple silicon) and Windows. No Rust toolchain.
pip install franken-networkx # with SciPy, for pagerank pip install 'franken-networkx[all]'Step 2
Switch on the backend
Once, at startup. Supported calls go to Rust; the rest stay in NetworkX.
import networkx as nx nx.config.backend_priority = ["franken_networkx"]Step 3
Or import it directly
No conversion on any call. The same names as NetworkX.
import franken_networkx as fnx G = fnx.karate_club_graph() fnx.betweenness_centrality(G)
Use it when
- You have NetworkX code and per-call time dominates. Switch on the backend and leave the code alone.
- You need the same output on every run and every machine: same input, same version, same answer.
- Your pipeline is long-lived, and a change in iteration order would be a silent bug downstream.
- You parse graphs from sources you don't trust and want a parser that refuses or records, never guesses.
Skip it when
- Your graphs are small (under about 10,000 nodes) and you run each analysis once. NetworkX is excellent there.
- You need a GPU. Look at cuGraph.
- You want a different model, such as igraph's integer vertex indices, and aren't tied to NetworkX's behaviour.
- You're on Python older than 3.10, or need a graph database rather than in-memory graphs.