如何注释用文字初始化的`OrderedDict`的类型?

问题描述 投票:0回答:1

假设我有以下内容:

from collections import OrderedDict
from dataclasses import dataclass


@dataclass
class HelloWorld:
    x: OrderedDict[str, int]


a = OrderedDict([("a", 0), ("c", 2), ("b", 1)])
HelloWorld(a) <--- # type error here

产生的类型错误是:

Argument of type "OrderedDict[Literal['a', 'c', 'b'], Literal[0, 2, 1]]" cannot be assigned to parameter "x" of type "OrderedDict[str, int]" in function "__init__"
  "OrderedDict[Literal['a', 'c', 'b'], Literal[0, 2, 1]]" is incompatible with "OrderedDict[str, int]"
    Type parameter "_KT@OrderedDict" is invariant, but "Literal['a', 'c', 'b']" is not the same as "str"
    Type parameter "_VT@OrderedDict" is invariant, but "Literal[0, 2, 1]" is not the same as "int

奇怪的是,这个非常相似的代码片段不会产生错误:

from collections import OrderedDict
from dataclasses import dataclass


@dataclass
class HelloWorld:
    x: OrderedDict[str, int]


HelloWorld(OrderedDict([("a", 0), ("c", 2), ("b", 1)])) # <--- no error
python python-typing ordereddictionary pylance pyright
1个回答
0
投票

使用

typing.cast

from collections import OrderedDict
from dataclasses import dataclass
from typing import cast


@dataclass
class HelloWorld:
    x: OrderedDict[str, int]


a = OrderedDict([("a", 0), ("c", 2), ("b", 1)])
HelloWorld(cast(OrderedDict[str, int], a))
© www.soinside.com 2019 - 2024. All rights reserved.