首页 > 解决方案 > How do I write a Python class that is a node in a linked list while using type hinting

问题描述

In Python 3.7, I have a dataclass that is a node in a linked list.

from dataclasses import dataclass

@dataclass
class Node(object):
    right: Node
    left: Node

The problem is that I get an inspection error in Pycharm:

Unresolved reference 'Node'

and this error when running

NameError: name 'Node' is not defined

dataclass requires I declare the type, so how do I solve this?

标签: python

解决方案


PEP 563 solves this.

By adding the following import, the type hinting is resolved later on.

from __future__ import annotations

推荐阅读