I have a generic function which takes any dictionary and returns a dictionary of the same structure.
from typing import TypeVar
from typing_extensions import TypedDict
DictT = TypeVar("DictT", bound=dict)
def myfunc(d: DictT) -> DictT:
return d
TD = TypedDict("TD", {
"b": int,
})
b: TD = {
"b": 2,
}
myfunc(b)
It passes mypy when I call it with a dictionary, but when I call the function with a TypedDict I get an error from mypy
16: error: Value of type variable "DictT" of "myfunc" cannot be "TD"
Why is TD
not accepted by the bound, and how do I make these types work correctly?
There is an open ticket regarding this functionality in MyPy here. The short version is, at the moment; you can't do it, and the best thing you can do is make your type Mapping[Any, Any]
. If you are needing more functionality of dict
other than it's Mapping
properties, you could try a Protocol
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With