6

Is it possible to reference the class currently being defined within the class definition?

from dataclasses import dataclass
from typing import List

@dataclass
class Branch:
    tree: List[Branch]

Error:

NameError: name 'Branch' is not defined
Druta Ruslan
  • 7,171
  • 2
  • 28
  • 38
Jack Brookes
  • 3,720
  • 2
  • 11
  • 22

1 Answers1

11

You haven't finished defining Branch when you use it in your type hint and so the interpreter throws a NameError. It's the same reason this doesn't work:

class T:
   t = T()

You can delay evaluation by putting it in a string literal like so

from dataclasses import dataclass
from typing import List

@dataclass
class Branch:
    tree: List['Branch']

This was actually decided to be a bad decision in the original spec and there are moves to revert it. If you are using Python 3.7 (which I'm guessing you are since you are using dataclasses, although it is available on PyPI), you can put from __future__ import annotations at the top of your file to enable this new behaviour and your original code will work.

FHTMitchell
  • 11,793
  • 2
  • 35
  • 47