【问题标题】:How to specify type hints for dictionary key and values of a dict? [duplicate]如何为字典键和字典值指定类型提示? [复制]
【发布时间】:2021-06-21 06:25:34
【问题描述】:

我有一本这样的字典:

d = { 'my_label': ClassInstance() }

我想指定类型提示以指示键是字符串,值是 ClassInstance 的实例。

这在 Python 3.8 中可行吗?

我找到了TypedDict,但这似乎试图指示一组固定的键。我会允许任何字符串作为键。

【问题讨论】:

  • 所示代码已经根据需要推断出d。你还需要什么?
  • 虽然是一个棘手的问题,但您为什么(实际上)要指定类型提示?另一种方法是将您的类实例序列化为 JSON 字符串,并在需要时将其转换回来。
  • 这能回答你的问题吗? Type hinting a collection of a specified type
  • 嗯,我正在学习更多关于 Python 的知识,但不知道这个问题的答案,所以......可能不实用,但没关系,对吧?如果投反对票的人能提供一些关于它有什么问题的信息,我将不胜感激。

标签: python python-3.x dictionary python-typing


【解决方案1】:

是的,在 Python 3.8 中是可能的

首次导入字典类型提示:

from typing import Dict

并添加类型提示如下:

d: Dict[str, ClassInstance] = { 'my_label': ClassInstance() }

在 Python 3.9 中,无需从输入 (link to 3.9 documentation) 中导入 Dict 即可:

d: dict[str, ClassInstance] = { 'my_label': ClassInstance() }

【讨论】:

    【解决方案2】:

    使用Dict[K, V]:

    from typing import Dict
    
    d: Dict[str, ClassInstance] = { 'my_label': ClassInstance() }
    

    【讨论】:

      猜你喜欢
      • 2016-09-26
      • 1970-01-01
      • 1970-01-01
      • 2018-12-04
      • 2021-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-24
      相关资源
      最近更新 更多