尝试注释哈希变量时,“ABCMeta”对象不可下标

dea*_*n44 14 python annotations python-3.x

以下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
Run Code Online (Sandbox Code Playgroud)

用作基类:

@dataclass(eq=True, frozen=True)
class HashLiteral(Expression):
    pairs: Mapping[Expression, Expression]
    ...
Run Code Online (Sandbox Code Playgroud)

Node 定义为:

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

尝试使用HashLiteral该类时出现错误:

pairs: Mapping[Expression, Expression]
TypeError: 'ABCMeta' object is not subscriptable
Run Code Online (Sandbox Code Playgroud)

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

Pat*_*ugh 34

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

  • 看起来这在 Python 3.9 版本中已更改,以便您现在可以从 collections.abc [文档](https://docs.python.org/3.9/library/typing.html#type-aliases) 导入 (4认同)