具有已知键类型的 Python 3 字典 [英] Python 3 dictionary with known keys typing
问题描述
我正在使用 Python 3 打字功能以实现更好的自动完成.
I'm using Python 3 typing feature for better autocomplete.
很多时候我有返回键/值(字典)和特定键的函数.超级简单的例子:
Many times I have functions that return key/value (dictionary) with specific keys. super simple example:
def get_info(name):
name_first_letter = name[0]
return {'my_name': name, 'first_letter': name_first_letter}
我想给这个函数添加类型提示,告诉其他使用这个函数的人期待什么.
I want to add type hinting to this function to tell others who use this function what to expect.
我可以这样做:
class NameInfo(object):
def __init__(self, name, first_letter):
self.name = name
self.first_letter = first_letter
然后将函数签名改为:
def get_info(name) -> NameInfo:
但是每个字典需要太多的代码.
But it requires too much code for each dictionary.
在这种情况下,最佳做法是什么?
What is the best practice in that case?
推荐答案
正如 Blckknght 所指出的,你和 Stanislav Ivanov 在评论中,你可以使用 NamedTuple
:
As pointed out by Blckknght, you and Stanislav Ivanov in the comments, you can use NamedTuple
:
from typing import NamedTuple
class NameInfo(NamedTuple):
name: str
first_letter: str
def get_info(name: str) -> NameInfo:
return NameInfo(name=name, first_letter=name[0])
从 Python 3.8 开始,您可以使用 TypedDict
与您想要的更相似:
Starting from Python 3.8 you can use TypedDict
which is more similar to what you want:
from typing import TypedDict
class NameInfo(TypedDict):
name: str
first_letter: str
def get_info(name: str) -> NameInfo:
return {'name': name, 'first_letter': name[0]}
这篇关于具有已知键类型的 Python 3 字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!