Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a dict bound TypeVar accept TypedDict

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?

like image 279
Gricey Avatar asked Oct 16 '25 14:10

Gricey


1 Answers

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.

like image 60
lewisjb Avatar answered Oct 18 '25 02:10

lewisjb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!