Hi all,
I wanted to bring into your attention about enabling support for generic TypedDicts.
The TypedDict PEP 589 does not necessarily talk about generics. And the runtime TypedDict implementation does not support it either.
Traceback (most recent call last):
File "testing.py", line 4, in <module>
class TD(Generic[T], TypedDict):
File "/usr/lib/python3.9/typing.py", line 1894, in __new__
raise TypeError('cannot inherit from both a TypedDict type '
TypeError: cannot inherit from both a TypedDict type and a non-TypedDict base class
Here I would like to discuss here if the implementation is done this way for a good reason (may be due to structural subtyping complications) and if there might still be a way to move
forward and add generic support for TypedDicts.
As you can see below there is a natural syntax for it (in both ways) and have backward compatibility.
from typing import TypedDict, TypeVar, Generic, List
T = TypeVar("T")
class TD(Generic[T], TypedDict):
f1: List[T]
R = TypeVar("R")
FileCachedData = TypedDict('FileCachedData', {'mtime': float, 'size': int, 'value': R})
def test_td(aa: TD[T], bb: TD[T]):
return aa["f1"], bb["f1"]
td1 = test_td({"f1": ["foo"]}, {"f1": ["bar"]})
reveal_type(td1) # info: Type of "td1" is "tuple[List[str], List[str]]"
test_td({"f1": ["foo"]}, {"f1": [1]}) # error
class TD2(TD[T]):
f2: T
td21: TD2[str] = {
'f1':["far"],
'f2':"boo"
}
reveal_type(td21["f1"]) # info: Type of "td21["f1"]" is "List[str]"
td22 = TD2(
f1=["far"],
f2="boo"
)
reveal_type(td22) # info: Type of "td22" is "TD2[str]"
td23: TD2[str] = {
'f1':[0],
'f2':"boo"
} # error
Thank you,
Samodya