【问题标题】:How to specify a return type for dictionary keys in Python?如何在 Python 中为字典键指定返回类型?
【发布时间】:2021-11-18 20:03:16
【问题描述】:

给定一个我想使用类型提示增强的功能(在 Python 3.9 中)

def my_func():
    return my_dict.keys() # origin of my_dict is irrelevant

我看到PEP 589this Stack Overflow question 描述了如何使用TypedDict 在字典中键入键和值。然而,这不是我试图达到的目标。

我想要字典键对象的返回类型。我知道one can convert the keys object into a list 使用list(my_dict),然后使用返回类型list[key_type]key_typeintstr 等)。但这是要走的路吗?

my_dict 的类型

>>> type(my_dict.keys())
<class 'dict_keys'>

但是,我无法像这样使用dict_keys

def my_func() -> dict_keys:
     return my_dict.keys()

Pylance 报告 my_dict.keys() 的类型为 _dict_keys[key_type, value_type]。为什么这种类型应该是“私有的”,它来自哪里?我们可以以某种方式将其用作返回类型吗?

【问题讨论】:

    标签: python


    【解决方案1】:

    对于 Python 3.9,您可以从 collections 模块中的 KeysView 输入提示您的函数:

    from collections import KeysView
    
    d = {'1': 1}
    
    
    def keys(d: dict[str, int]) -> KeysView[str]:
        return d.keys()
    

    文档:https://docs.python.org/3/library/collections.abc.html#collections.abc.KeysView

    对于旧版本,请改用typing.KeysView

    【讨论】:

    • 谢谢,这解决了我的问题?。请注意,我们也可以直接在Python 3.9 中使用dict,而不是Dict[...](参见PEP 585),只是为了改进这个答案;)
    猜你喜欢
    • 2021-06-21
    • 2013-05-25
    • 1970-01-01
    • 2021-10-20
    • 2019-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多