问题
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