2

I'm looking for typing a class with recursive field

I try the following code:

class Heh:
  child_hehs: list[Heh]

but i got following error

NameError: name 'Heh' is not defined

so I try another code:

class MetaHeh(Heh):
  pass

class Heh:
  child_hehs: list[MetaHeh]

and i got following error again:

NameError: name 'Heh' is not defined

How can i implement this code with typing?

AliReza Beigy
  • 559
  • 1
  • 8
  • 19
  • Either use a string or import the future behaviour; see https://stackoverflow.com/a/59181507/3001761 for the former, https://stackoverflow.com/q/33533148/3001761. – jonrsharpe Jan 26 '21 at 21:05
  • While above questions are related - this is different scenario. – napuzba Jan 27 '21 at 15:37

1 Answers1

2

Use the name of the recursive type in its declaration. For example:

class Heh:
  child_hehs: list['Heh']

If you can use python 3.7.0b1 and above you can use Postponed Evaluation of Annotations.

from __future__ import annotations 
class Heh:     
    child_hehs: list[Heh]

This feature is expected to become part of the language in python 3.10 (in other words, without __future__ import).

napuzba
  • 6,033
  • 3
  • 21
  • 32