0

Is there a way to define a parameter's type in a class such that the type references itself?

For example, the following won't run:

from typing import List

class Node:
    def __init__(self, val: int=0, neighbors: List[Node]=[]):
        self.val = val
        self.neighbors = neighbors

Error:

Traceback (most recent call last):
  File "node.py", line 3, in <module>
    class Node:
  File "node.py", line 4, in Node
    def __init__(self, val: int=0, neighbors: List[Node]=[]):
NameError: name 'Node' is not defined
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
bli00
  • 2,215
  • 2
  • 19
  • 46

1 Answers1

0

The best solution here is to use Python 3.7+, which adds support for PEP 563: Postponed evaluation of annotations. All you need to do in that case is add:

from __future__ import annotations

to the top of your source file, which enables deferred annotation evaluation (making your code run faster by not even trying to evaluate the annotations unless running under an analyzer like mypy).

Without 3.7+, you're stuck with the old PEP 484 forward references approach of using string annotations:

def __init__(self, val: int=0, neighbors: List['Node']=[]):

Note the quotes around Node, which defers the evaluation of the type on the assumption that it will be defined later.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271