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

Spl*_*nes 3 python

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

def my_func():
    return my_dict.keys() # origin of my_dict is irrelevant
Run Code Online (Sandbox Code Playgroud)

我看过PEP 589和这个 Stack Overflow 问题,描述了如何使用TypedDict. 然而,这不是我试图实现的目标。

我想要字典键对象的返回类型。我知道可以使用将键对象转换为列表list(my_dict),然后使用返回类型list[key_type](使用key_typebeingint等str)。但这是要走的路吗?

类型my_dict

>>> type(my_dict.keys())
<class 'dict_keys'>
Run Code Online (Sandbox Code Playgroud)

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

def my_func() -> dict_keys:
     return my_dict.keys()
Run Code Online (Sandbox Code Playgroud)

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

rda*_*das 10

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

from collections import KeysView

d = {'1': 1}


def keys(d: dict[str, int]) -> KeysView[str]:
    return d.keys()
Run Code Online (Sandbox Code Playgroud)

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

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