Typing Stubs for NetworkX
Typing stubs for the `networkx` library. This package provides external type annotations, allowing static type checkers like MyPy and PyRight to analyze code that uses `networkx` for graph manipulation. It is an automatically generated component of the `typeshed` project and aims to provide accurate annotations for specific `networkx` versions. Stubs are released frequently, often daily, by typeshed's automated processes.
Warnings
- gotcha Ensure the `types-networkx` version aligns with your installed `networkx` version. Mismatched versions can lead to incorrect or incomplete type checking results, as the stubs might not reflect the exact API of the `networkx` library you are using.
- gotcha Some `networkx` classes might be generic in stubs (e.g., `DiGraph[NodeT]`) but not at runtime, which can cause `TypeError: type 'DiGraph' is not subscriptable` when used with other libraries like Pydantic that inspect runtime types.
- breaking While `types-networkx` provides stubs for the `networkx` API, `networkx` itself has undergone significant breaking changes between major versions (e.g., 1.x to 2.0, and 2.x to 3.0), particularly regarding iterator vs. view behavior, and the replacement of `numpy.matrix` with `numpy.ndarray`. Type stubs will reflect the target `networkx` version's API, but old code written for earlier `networkx` versions may still break at runtime even with correct stubs if not migrated.
Install
-
pip install types-networkx -
pip install networkx
Imports
- Graph
import networkx as nx my_graph: nx.Graph[str] = nx.Graph()
- DiGraph
from networkx import DiGraph my_digraph: DiGraph[int] = DiGraph()
Quickstart
import networkx as nx
def create_and_analyze_graph(nodes: list[str], edges: list[tuple[str, str]]) -> tuple[nx.Graph[str], int]:
G: nx.Graph[str] = nx.Graph()
G.add_nodes_from(nodes)
G.add_edges_from(edges)
num_nodes: int = G.number_of_nodes()
return G, num_nodes
if __name__ == '__main__':
nodes_data = ['A', 'B', 'C', 'D']
edges_data = [('A', 'B'), ('B', 'C'), ('C', 'D'), ('D', 'A')]
graph, count = create_and_analyze_graph(nodes_data, edges_data)
print(f"Created graph with {count} nodes and {graph.number_of_edges()} edges.")
# Example of type checking at work: attempting to add a non-string node would be flagged by a type checker
# graph.add_node(123) # This line would cause a type error with strict type checking