具有已知键输入的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
,然后将函数签名更改为:
and then change the function signature to:
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在评论中都可以使用
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屋!