How to declare that a camp has the same kind of class?

Asked

Viewed 56 times

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

1 answer

4

Solution

Change:

next: Optional[Node[T]]

To:

next: Optional['Node[T]'] # agora como string

Problem and motivation

The problem is that at the point where the next the class is being built Node does not yet exist. The error itself is indicative of this:

Unresolved Reference 'Node'

Looking at the PEP 484 in Forward Declarations can see the same problem being detailed:

The Current Proposal is admittedly sub-optimal when type hints must contain forward References. Python requires all Names to be defined by the time they are used

Translating:

The current proposal is clearly not optimal for types with future references. Python requires all names to be defined at the time they are used.

Then indicate how to solve:

Our Solution, which isn’t particularly Elegant, but gets the job done, is to allow using string literals in Annotations

Translating:

Our solution that is not particularly elegant, but that solves the problem, is to enable the use of strings in annotations.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.