-
-
Notifications
You must be signed in to change notification settings - Fork 2k
Closed as not planned
Description
Please forgive me if I am missing something.
I am attempting to strictly type check my networkx code using mypy --strict
eg:
# thing_1_fails_mypy_strict_but_runs.py
import networkx as nx
def modify_graph(g: nx.Graph) -> None:
g.add_node("a")
g: nx.Graph = nx.Graph()
modify_graph(g)thing_1_fails_mypy_strict_but_runs.py:3: error: Missing type parameters for generic type "Graph" [type-arg]
thing_1_fails_mypy_strict_but_runs.py:6: error: Missing type parameters for generic type "Graph" [type-arg]
In order to get it to pass I happily add a str type parameter for the generic type "Graph"
# thing_2_passes_mypy_strict_but_runtime_error.py
import networkx as nx
def modify_graph(g: nx.Graph[str]) -> None:
g.add_node("a")
g: nx.Graph[str] = nx.Graph()
modify_graph(g)But now it fails at runtime with the following error:
(.venv) PS C:\test_typing_of_networkx\src> python .\thing_2_passes_mypy_strict_but_runtime_error.py
Traceback (most recent call last):
File "C:\test_typing_of_networkx\src\thing_2_passes_mypy_strict_but_runtime_error.py", line 3, in <module>
def modify_graph(g: nx.Graph[str]) -> None:
~~~~~~~~^^^^^
TypeError: type 'Graph' is not subscriptable
I have found a way to get past this is to put the type hint in quotes, though it only seems necessary in function definition parameter lists (in my brief testing).
# thing_3_passes_mypy_strict_and_runs.py
import networkx as nx
def modify_graph(g: "nx.Graph[str]") -> None:
g.add_node("a")
g: nx.Graph[str] = nx.Graph()
modify_graph(g)These are the packages I have, and I am running Python 3.13.5
mypy 1.18.2
mypy_extensions 1.1.0
networkx 3.5
numpy 2.3.3
types-networkx 3.5.0.20251001
Have I missed something that would allow the type hinting to work without quoting (in function definitions).
The run-time error TypeError: type 'Graph' is not subscriptable caught me by surprise.
Cheers,
Ben.
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels