0

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].

Juicy
  • 11,840
  • 35
  • 123
  • 212

1 Answers1

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].
ewz93
  • 2,444
  • 1
  • 4
  • 12