我有一个字典,
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
。如何正确注释这个变量?
我对这样一个字典的用例很好奇,但可能有效的方法如下:
from typing import TypedDict
class Demo:
pass
class Foo(TypedDict):
int: int
str: str
Demo: Demo
foo = Foo(int=5, str="Hi", Demo=Demo())