Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference class type in dataclass definition

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
like image 959
Jack Brookes Avatar asked Mar 06 '23 18:03

Jack Brookes


1 Answers

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.

like image 75
FHTMitchell Avatar answered Mar 31 '23 14:03

FHTMitchell