在 Python 3.8 中没有附加 class 的 TypedDict 的键入键、值

Typing Key, Value of a TypedDict without additional class in Python 3.8

我想使用 Python 3.8 中的打字模块。 Python 3.8 在打字模块中加入了 TypedDict。 我有一个带有这样参数的函数: 从输入导入

def groupDataFrame(df: pd.DataFrame, somelist: List[str], somedict: TypedDict[str: Callable]:
    pass

但它不允许我像这样指定字典,抛出 TypeError: TypeError: '_TypedDictMeta' object is not subscriptable

有一个解决方案利用了额外的 class,但这是一个非常丑陋的解决方案:

How to get key type from pythons TypedDict

知道如何在没有额外 class 的情况下做到这一点吗?

TypedDict不能下标;你打算实例化或子类化一个 according to the docs:

Point2D = TypedDict('Point2D', x=int, y=int, label=str)
Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})

考虑到这一点,您可以在签名中直接插入:

def x(a: TypedDict('A', x=int)):
  pass