PEP 695: Type Parameter Syntax

I’m a bit concerned that the proposed syntax seems to preclude the possibility of ever adding something like a TypeVarDict to Python (because the syntax **Tdict is being taken by ParamSpec). I think you said before that there doesn’t seem to be a use case for TypeVarDict, but what about something like a pandas dataframe? Each column doesn’t only have its own type – it also has its own name:

>>> df = pd.DataFrame(data={"col1": [1.5, 2.3], "col2": [True, False]})
>>> df.dtypes
col1    float64
col2       bool
dtype: object
>>> df.loc[:, "col1"]
0    1.5
1    2.3
Name: col1, dtype: float64

So, it seems to me like if you really want to model this with types, you need a TypeVarDict. It might look something like this (using the Map operator that was originally part of PEP 646; Map[List, (int, bool)]==(List[int], List[bool])):

Tdict = TypeVarDict("Tdict")

class DataFrame[**Tdict]:
    def __init__(self, data: Map[List, Tdict]): ...
    @property
    def loc(self) -> Map[Series, Tdict]: ...

Cols = TypedDict("Cols", {"col1": numpy.float64, "col2": bool})

df: DataFrame[Cols] = DataFrame(
        data={"col1": [1.5, 2.3], "col2": [True, False]})
col1: Series[numpy.float64] = df.loc["col1"]

I’m not necessarily saying it’s a good idea, but why not allow the future possibility?

5 Likes