Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python mypy`TypedDict的工厂函数`_Python_Python 3.x_Mypy - Fatal编程技术网

Python mypy`TypedDict的工厂函数`

Python mypy`TypedDict的工厂函数`,python,python-3.x,mypy,Python,Python 3.x,Mypy,我希望能够编写一个函数,检查字典是否符合我的TypedDict,但是我无法正确获取泛型类型。因此,结果函数应该类似于: T = typing.Generic('T', bound=...) # This is `bound=...` something I want to find out def check_typeddict(value: dict, to_type: typing.Type[T]) -> T: # do some type checking retu

我希望能够编写一个函数,检查字典是否符合我的
TypedDict
,但是我无法正确获取泛型类型。因此,结果函数应该类似于:

T = typing.Generic('T', bound=...) # This is `bound=...` something I want to find out

def check_typeddict(value: dict, to_type: typing.Type[T]) -> T:
    # do some type checking
    return typing.cast(T, value)

check_type(MyTypedDict, {'a': 5})

使用
TypedDict
dict
作为
bound
值是不可行的,这是不可能的(现在)还是我遗漏了其他东西?

你不应该使用
Generic
——你想要的是
TypeVar
。我们使用
Generic
来声明某些类应该被视为泛型;我们使用
TypeVar
创建一个类型变量(然后我们可以使用它来帮助创建泛型类或函数)

在调用
check\u-type
(可能也应该是
check\u-typeddict
)时,还交换了参数

把这些放在一起,代码的功能版本如下所示:

from typing import TypeVar, Type, cast
from mypy_extensions import TypedDict

class MyTypedDict(TypedDict):
    a: int
    b: int

T = TypeVar('T')

def check_typeddict(value: dict, to_type: Type[T]) -> T:
    # do some type checking
    return cast(T, value)

out = check_typeddict({'a': 5}, MyTypedDict)
reveal_type(out)  # Mypy reports 'MyTypedDict'

在这种情况下不需要绑定。

哦,很抱歉我使用了
TypeVar
,这只是一个打字错误。很抱歉。不使用基的问题是,任何值都可以传递给
check\u typeddict
,而不仅仅是
typeddict
。似乎绑定到
映射
是可行的,但是仍然允许传递
dict
,我更愿意拒绝。