15

With the recent introduction to python dataclass decorator, its been quite easy writing model classes.

However I am not sure about how to use with the context of self-referencing structure/model class - e.g. LinkedList's internal ListNode/Node model class.

>>> from dataclasses import dataclass
>>> from typing import Type
>>>
>>> @dataclass
... class Node:
...     data: int
...     link: Node
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in Node
NameError: name 'Node' is not defined
>>>
>>>
>>> @dataclass
... class Node:
...     data: int
...     link: Type[Node] # have tried Type hinting 
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in Node
NameError: name 'Node' is not defined
>>>

I may be misunderstood the concept of dataclass with respect to self-referencing structure.

Is it possible to use dataclass decorator in such context - or I am missing some important concepts?

Thanks in advance.

Kunal
  • 597
  • 7
  • 19
  • 4
    I am not an expert on annotations, but try `Type["Node"]` to make a forward ref. – wim Aug 15 '18 at 16:07
  • 1
    Following snippet solved the problem - thanks Wim for pointing out. @dataclass ... class Node: ... data: int ... link: Type['Node'] – Kunal Aug 16 '18 at 05:31
  • 4
    Just use a `from __future__ import annotations` declaration and it will work. See [this answer](https://stackoverflow.com/a/52631754/974555). – gerrit Oct 03 '18 at 16:33

0 Answers0