Search code examples
pythontyping

Recursive class typing in python


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?


Solution

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