'Referencing this custom class with typing [duplicate]

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 1:[1]

Check out How do I type hint a method with the type of the enclosing class?. You can either:

  1. Use from __future__ import annotations at the top of the file and then use Node as you did.
  2. Use a string ('Node'), see @Diptangsu Goswami's comment.
  3. From Python 3.11 and onwards (not out yet) you will be able to use from typing import Self and then Optional[Self].

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ewz93