'ABCMeta' 尝试注释散列变量时对象不可订阅

'ABCMeta' object is not subscriptable when trying to annotate a hash variable

以下dataclass

from abc import ABC
from collections.abc import Mapping
from dataclasses import dataclass, field

@dataclass(eq=True, order=True, frozen=True)
class Expression(Node, ABC):
    def node(self):
        raise NotImplementedError

用作基础 class 用于:

@dataclass(eq=True, frozen=True)
class HashLiteral(Expression):
    pairs: Mapping[Expression, Expression]
    ...

Node 定义为:

@dataclass(eq=True, frozen=True)
class Node:
    def __str__(self) -> str:
        raise NotImplementedError

尝试使用 HashLiteral class 时出现错误:

pairs: Mapping[Expression, Expression]
TypeError: 'ABCMeta' object is not subscriptable

我上面 pairs 的注释有什么问题?

您应该使用 typing.Mapping 而不是 collections.abc.Mappingtyping 包含各种类型的许多泛型版本,旨在用于类型提示。根据 mypy documentationtyping 类 和 collections.abc 类 之间存在一些差异,但他们不清楚这些差异到底是什么。