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?
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?
For Python 3.9, you can KeysView
from the collections
module to type hint your 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
For older versions, use typing.KeysView
instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.