【发布时间】:2021-10-20 03:10:27
【问题描述】:
我有一个函数,它返回一个始终具有相同键的字典(通过网络发送并使用 json“字符串化”)。基本上我的功能是这样的:
def getTemps(self) -> dict:
"""
get room and cpu temperature in °C as well as humidity in %
"""
# send temperature request to server
msg = {'type':'req', 'reqType':'temps'}
self.send(msg)
res = self.recieve() # get response
return res
你从这个函数中得到的字典总是看起来像这样:
{'Room':float, 'CPU':float, 'hum':float}
所以我想知道是否有办法指定函数的返回类型,以便您知道字典有哪些键:
def getTemps(self) -> Dict['Room':float, 'CPU':float, 'hum':float]
但这不起作用,因为它只在将鼠标悬停在函数上时显示Dict[slice, slice, slice](我使用的是 vscode)。
我不认为这是非常有用的东西,但它可以让你的代码看起来更好,也更容易被其他人使用。因此,如果有人知道这是否可能以及如何实现,我将非常感谢您的回复!
【问题讨论】:
-
这能回答你的问题吗? Python 3 dictionary with known keys typing
标签: python-3.x key type-hinting python-3.10