如何为将类映射到该类的实例的字典添加类型提示?

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

我有一个字典,

foo
,它将类型(类)映射到该类型的实例:

class Demo:
    pass


foo = {
    int: 5,
    str: "Hi",
    Demo: Demo()
}

如何向此变量添加类型提示,以允许类型检查器(例如

mypy
pyright
)确保此变量的内容正确?

我尝试使用类型变量:

from typing import TypeVar

T = TypeVar("T")


class Demo:
    pass


foo: dict[type[T], T] = {
    int: 5,
    str: "Hi",
    Demo: Demo()
}

但是

pyright
只是抱怨:
Type variable "T" has no meaning in this context
。如何正确注释这个变量?

python mypy python-typing
1个回答
0
投票

我对这样一个字典的用例很好奇,但可能有效的方法如下:

from typing import TypedDict


class Demo:
    pass


class Foo(TypedDict):
    int: int
    str: str
    Demo: Demo


foo = Foo(int=5, str="Hi", Demo=Demo())
© www.soinside.com 2019 - 2024. All rights reserved.