I want to define a Node for a Linked List, using type hints. An instance of Node needs a reference to another instance of Node, so I want to accept an optional parameter of type Node in my __init__.
I tried this:
from typing import Optional
class Node:
def __init__(self, value: int, next: Optional[Node] = None):
pass
I get an error: Node is not defined from Optional[Node].
>Solution :
Check out How do I type hint a method with the type of the enclosing class?. You can either:
- Use
from __future__ import annotationsat the top of the file and then useNodeas you did. - Use a string (
'Node'), see @Diptangsu Goswami’s comment. - From Python 3.11 and onwards (not out yet) you will be able to use
from typing import Selfand thenOptional[Self].