Self-reference or forward-reference of type annotations in Python

Viewed 21742

I'm trying to figure out how self-reference of types work with python3's type annotations - the docs don't specify anything regarding this.

As an example:

from typing import TypeVar, Optional, Generic

T = TypeVar('T')
class Node(Generic[T]):
    left = None
    right = None
    value = None

    def __init__(
        self, value: Optional[T],
        left: Optional[Node[T]]=None,
        right: Optional[Node[T]]=None,
    ) -> None:
        self.value = value
        self.left = left
        self.right = right

This code generates the error:

Traceback (most recent call last):
  File "node.py", line 4, in <module>
    class Node(Generic[T]):
  File "node.py", line 12, in Node
    right: Optional[Node[T]]=None,
NameError: name 'Node' is not defined

This is using Python 3.5.1

1 Answers
Related