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

Viewed 1075

Given a function that I want to enhance using type hinting (in 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. However, this is not what I try to achieve.

I want a return type for the dictionary keys 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.). But is this the way to go?

Type of my_dict

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

However, I was not able to use dict_keys like this:

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

Pylance reports that my_dict.keys() is of type _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?

1 Answers
Related