【问题标题】:Python function return type hints with fixed dictionary keys具有固定字典键的 Python 函数返回类型提示
【发布时间】: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.x key type-hinting python-3.10


【解决方案1】:

考虑一下:

class Message:
    def __init__(self,room,cpu,hum):
        self.Room = room
        self.CPU = cpu
        self.hum = hum

return Message(room,cpu,hum) 或在必要时在类中定义一个将其转换为dict 的方法。

这可能是唯一的方法。

更新:这既不是唯一也不是最好的方法,请参阅 cmets。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-25
  • 1970-01-01
  • 2018-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-07
相关资源
最近更新 更多