Search code examples
pythonpython-typingpython-dataclasses

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

Solution

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