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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With