简体   繁体   中英

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

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.

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:
  ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM