mypy `TypedDict` 的工厂函数 [英] Factory function for mypy `TypedDict`

查看:40
本文介绍了mypy `TypedDict` 的工厂函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够编写一个函数来检查字典是否符合我的 TypedDict,但是我无法正确获取泛型类型.所以结果函数应该是这样的:

I want to be able to write a function that checks if a dictionary confirms to my TypedDict, however I can't get the generic type right. So the resulting function should be something like:

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})

像使用 TypedDictdict 作为 bound 值之类的事情不起作用,这根本不可能(还)还是我我错过了什么?

Things like using TypedDict or dict for the bound value do not work, is this simply not possible (yet) or I'm I missing something else?

推荐答案

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

You shouldn't be using Generic -- you want TypeVar instead. We use Generic to declare that some class ought to be treated as being generic; we use TypeVar to create a type variable (which we can then use to help make generic classes or functions).

您还可以在对 check_type 的调用中交换参数(也应该是 check_typeddict).

You also have the arguments swapped in your your call to check_type (which should also probably be check_typeddict).

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

Putting these all together, a functioning version of your code looks like this:

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'

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

No bound should be necessary in this case.

这篇关于mypy `TypedDict` 的工厂函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆