【问题标题】:Typing Key, Value of a TypedDict without additional class in Python 3.8在 Python 3.8 中没有附加类的 TypedDict 的键入键、值
【发布时间】:2020-11-12 23:25:18
【问题描述】:

我想在 Python 3.8 中使用 Typing 模块。 Python 3.8 在 Typing 模块中有一个 TypedDict。 我有一个带有如下参数的函数: 从输入导入

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

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

有一个使用附加类的解决方案,但这是一个非常丑陋的解决方案:

How to get key type from pythons TypedDict

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

【问题讨论】:

  • 对,因为这不是它的本意

标签: python python-typing


【解决方案1】:

你不能下标 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

【讨论】:

    猜你喜欢
    • 2021-08-31
    • 1970-01-01
    • 1970-01-01
    • 2020-05-17
    • 2022-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多