Factory function for mypy `TypedDict`

杀马特。学长 韩版系。学妹 提交于 2021-01-29 03:02:48

问题


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

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?


回答1:


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

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.



来源:https://stackoverflow.com/questions/52747473/factory-function-for-mypy-typeddict

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!