简体   繁体   English

如何为 Python 中的字典键指定返回类型?

[英]How to specify a return type for dictionary keys in Python?

Given a function that I want to enhance using type hinting (in Python 3.9) :给定一个 function 我想使用类型提示来增强(在 Python 3.9 中)

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

I've seen PEP 589 and this Stack Overflow question describing how to type the keys and values in a dict using TypedDict .我看过PEP 589这个 Stack Overflow 问题,描述了如何使用TypedDict在 dict 中键入键和值。 However, this is not what I try to achieve.然而,这不是我想要达到的。

I want a return type for the dictionary keys object.我想要字典键 object 的返回类型。 I know one can convert the keys object into a list using list(my_dict) and then use the return type list[key_type] (with key_type being int , str etc.).我知道可以使用list(my_dict)将键 object 转换为列表,然后使用返回类型list[key_type]key_typeintstr等)。 But is this the way to go?但这是通往 go 的路吗?

Type of my_dict my_dict的类型

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

However, I was not able to use dict_keys like this:但是,我无法像这样使用dict_keys

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

Pylance reports that my_dict.keys() is of type _dict_keys[key_type, value_type] . Pylance 报告my_dict.keys()属于_dict_keys[key_type, value_type]类型。 Why is this type supposed to be "private" and where is it coming from?为什么这种类型应该是“私有的”,它来自哪里? Can we somehow use it as return type?我们可以以某种方式将其用作返回类型吗?

For Python 3.9, you can KeysView from the collections module to type hint your function:对于 Python 3.9,您可以从KeysView模块中的collections输入提示您的 function:

from collections import KeysView

d = {'1': 1}


def keys(d: dict[str, int]) -> KeysView[str]:
    return d.keys()

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

For older versions, use typing.KeysView instead.对于旧版本,请改用typing.KeysView

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM