FrankenNetworkX

Guide/How it works

Working With Attributes

1 min readFrom the README

On this page 6
Setting attributes at construction timeBulk attribute updatesReading edge attributes in algorithmsReading attributes from algorithm outputAttribute mutation outside an algorithm callAttribute serialization

NetworkX's killer feature is arbitrary edge / node / graph attributes. fnx preserves that contract exactly. A few patterns worth knowing.

Setting attributes at construction time

import franken_networkx as fnx

G = fnx.Graph()
G.add_node("alice", role="engineer", since=2020)
G.add_node("bob",   role="manager",  since=2018)
G.add_edge("alice", "bob", weight=3.0, since=2022, project="franken_networkx")

print(G.nodes["alice"])
# {'role': 'engineer', 'since': 2020}
print(G.edges["alice", "bob"])
# {'weight': 3.0, 'since': 2022, 'project': 'franken_networkx'}

Bulk attribute updates

# Bulk-set node attributes from a dict.
fnx.set_node_attributes(G, {"alice": "Engineering", "bob": "Management"}, "team")

# Bulk-set edge attributes.
fnx.set_edge_attributes(G, {("alice", "bob"): {"status": "active"}})

print(G.nodes["alice"]["team"])     # → "Engineering"
print(G.edges["alice", "bob"])
# {'weight': 3.0, 'since': 2022, 'project': 'franken_networkx', 'status': 'active'}

set_node_attributes and set_edge_attributes are mutation-preserving dispatchables: when called via the NetworkX backend they route into fnx and the mutation lands on the original graph.

Reading edge attributes in algorithms

The weight= kwarg on weighted algorithms is the attribute name to read:

# A graph carrying BOTH attributes the examples below read, so each call means
# something different on the same edges. Named `W` rather than `G` so it does not
# shadow the running example graph used by the surrounding sections.
W = fnx.Graph()
W.add_edge("a", "m", weight=1.0, cost=5.0, toll=2.0)
W.add_edge("m", "z", weight=1.0, cost=5.0, toll=2.0)
W.add_edge("a", "z", weight=3.0, cost=1.0, toll=0.0)

fnx.shortest_path(W, "a", "z", weight="cost")     # use the "cost" attribute → ['a', 'z']
fnx.shortest_path(W, "a", "z", weight="weight")   # default                  → ['a', 'm', 'z']
fnx.shortest_path(W, "a", "z", weight=None)       # ignore weights → BFS     → ['a', 'z']
fnx.shortest_path(W, "a", "z", weight=lambda u,v,d: d.get("cost", 1) + d.get("toll", 0))
# ↑ callable form: fnx accepts it but may delegate to nx depending on the algorithm
#   (see docs/delegation_ledger.md for the per-algorithm contract)

Reading attributes from algorithm output

Many algorithms return the original graph's attributes as part of their output. The SubgraphView returned by G.subgraph([...]) shares the underlying attribute store, so mutations propagate. Use G.subgraph([...]).copy() to take a snapshot.

Attribute mutation outside an algorithm call

G.edges["alice", "bob"]["weight"] = 5.0  # direct mutation
# ↑ updates the Python-side attribute dict. The next *weighted* algorithm
#   call (one that reads "weight" or another attribute) invokes
#   _sync_rust_edge_attrs(G) under the hood to push the new value down
#   into the Rust adjacency before running.

The sync helper only runs ahead of algorithms that read edge attributes (dijkstra, bellman_ford, weighted matching, and so on), not before every dispatch. If you're profiling an attribute-heavy hot loop and want to amortize the sync cost, the canonical pattern is to batch mutations through set_edge_attributes(G, {...}) (one sync at the end of the batch) rather than per-mutation G[u][v][k] = v.

Attribute serialization

Attributes survive a round-trip through every native I/O format:

import os, tempfile

# Written into a temp dir so running the docs verifier does not leave files in
# the working tree; in your own code these are just paths.
with tempfile.TemporaryDirectory() as _io_dir:
    fnx.write_graphml(G, os.path.join(_io_dir, "g.xml"))   # types preserved via <data attr.type=...>
    fnx.write_gml(G,     os.path.join(_io_dir, "g.gml"))   # typed scalars
    fnx.write_gexf(G,    os.path.join(_io_dir, "g.gexf"))  # typed attributes
data = fnx.node_link_data(G)      # JSON with type tags

The GraphML / GML / GEXF writers all emit typed attribute markers (long, double, string, boolean) so type identity survives. JSON node-link uses Python's standard json library type mapping.