I'm trying to implement Nodes and Edges for a graph. Here is my code:
from typing import NamedTuple, List
class Node(NamedTuple):
    name: str
    edges: List[Edge]
class Edge(NamedTuple):
    src: Node
    dest: Node
This raises an error because the Edge type is not defined when Node is created.
NameError: name 'Edge' is not defined
Switching the definitions around doesn't work because Edge also refers to Node.
How can I make it work?
Use string literals.
from typing import NamedTuple, List
class Node(NamedTuple):
    name: str
    edges: List['Edge']
class Edge(NamedTuple):
    src: Node
    dest: Node
The details are in PEP-484, under the "Forward References" section:
When a type hint contains names that have not been defined yet, that definition may be expressed as a string literal, to be resolved later.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With