Reputation: 21
I wrote some python code which constructs graphs as dict
similar to standard lib's graphlib. Graph construction maintains a stack of partial graphs with "exit" vertices. Vertices are tuple[Graph, str]
to mutate the node once the destination of that vertex becomes known. Instead of creating a special-purpose type, the partial graph plus vertices are smushed together into a tuple, a little like lisp forms. What type declaration can I use for these? I tried the below but "..." is only allowed as the second of two arguments
from typing import Optional
Graph = dict[str, Optional["Graph"]] # None is a terminal
GraphAndVertices = tuple[Graph, tuple[Graph, str], ...]
Upvotes: 1
Views: 1649
Reputation: 458
This is now supported in Python 3.11 using the new type hints for Variadic Generics, specifically for unpacking unbounded tuples here
The type hint now could be written as
GraphAndVertices = tuple[Graph, *tuple[tuple[Graph, str], ...]]
Upvotes: 1
Reputation: 168913
As discussed in the comments, I don't think the tuple type is equipped for that sort of annotation.
I think you might have a better time rewriting things to
from typing import Optional
Graph = dict[str, Optional["Graph"]]
GraphAndVertices = tuple[Graph, tuple[tuple[Graph, str], ...]]
i.e. keeping the "tail" in another variable-length tuple of graph/str pairs.
Upvotes: 1