3
I am trying to add typing to the Python code, and I came across an error when trying to annotate the type of a property that must have the same type of class in which it is declared:
from typing import Generic, TypeVar, Optional
T = TypeVar('T')
class Node(Generic[T]):
value: T
next: Optional[Node[T]]
^ esse tipo não é reconhecido
I know the way I wrote down the type is correct, because when I use this same type in another class, I have no mistakes:
class LinkedList(Generic[T]):
head: Optional[Node[T]]
tail: Optional[Node[T]]
^ aqui funciona normalmente
But this syntax is not valid within the class Node
. How can I type the property next
inside Node
?
If you are Python >= 3.7, you can use
from __future__ import annotations
(put at the beginning of the file). They say that from Python 3.10 this code will work smoothly (but I installed the version pre-release and it still hasn’t worked, so let’s wait...)– hkotsubo