Is there a way to describe/type-hint the contents of a function's parameters?

半腔热情 提交于 2019-12-23 15:41:12

问题


I'm trying to learn how to better document my code. Describing a function and just hinting that it receives dict seems to leave any future reader rather short on information though.

Is it common at all to do the following? Or is there maybe another way I've missed reading on the subject?

    def add_control(self, ctrl_data: dict):
        """

        :param ctrl_data:
            - name: str
            - channel: int
            - control_channel_id: int
            - default_position: int
        :type ctrl_data: dict
        """

Edit: Please actually read a bit into the question before blindly calling it a duplicate. My question already shows that I know what type-hinting is, I'm looking for an answer on a very specific part of how type-hinting works when dealing with nested objects in parameters.


回答1:


  • If you want to use a dict you should look into TypedDict. TypedDict: Type Hints for Dictionaries with a Fixed Set of Keys.
from typing import TypedDict

class CtrlData(TypedDict):
  name: str
  channel: int
  control_channel_id: int
  default_position: int

def add_control(self, ctrl_data: CtrlData):
  ...
  • To better document the code you should add a return type.
def add_control(self, ctrl_data: CtrlData) -> TReturn:
  ...
  • You could also change the function signature and leave the caller to unpack the dict. I'd say that's clearer when you have just a few parameters.
def add_control(
  self,
  name: str,
  channel: int,
  control_channel_id: int,
  default_position: int
  ) -> TReturn:
  ...


来源:https://stackoverflow.com/questions/58325693/is-there-a-way-to-describe-type-hint-the-contents-of-a-functions-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!