7

How can I have a member field of a dataclass same as the class name in python3.7+ ? I am trying to define a class like so (which can be done in Java or C++) -- which might be used as a class for LinkedList node

@dataclass
class Node:
  val:str
  next:Node
  prev:Node

However, all I get is NameError: name 'Node' is not defined. What should be the correct way to have self referential member variables in dataclasses

exifguy
  • 650
  • 7
  • 16
  • Does [this](https://stackoverflow.com/questions/9305751/how-to-force-ensure-class-attributes-are-a-specific-type) answer your question? – bhristov Jun 22 '20 at 19:15

2 Answers2

10

You need to add the following import to your file

from __future__ import annotations

This enables deferred annotations, which are proposed in PEP 563. Deferred annotations allow you to reference a class that is not yet defined, in your example the Node class is not defined when you are still in it's body

Iain Shelvington
  • 31,030
  • 3
  • 31
  • 50
7

Another way is to use a TypeVar:

from dataclasses import dataclass
from typing import TypeVar

Node = TypeVar("Node")

@dataclass
class Node:
  val:  str
  next: Node
  prev: Node

This is also useful when dealing with annotations for methods of a class.

oblalex
  • 5,366
  • 2
  • 24
  • 25