4

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.

NoSplitSherlock
  • 605
  • 4
  • 19
  • 1
    Possible duplicate of [What are Type hints in Python 3.5](https://stackoverflow.com/questions/32557920/what-are-type-hints-in-python-3-5) – Georgy Oct 10 '19 at 14:55
  • @Georgy I know what type-hints in general are and that linked question does not tell me anything about what I'm asking here. I can't seem to find any material on this specific subject. To be more clear, I'm interested in what you might call "nested type-hinting". – NoSplitSherlock Oct 10 '19 at 14:58
  • 3
    Are you looking for a [`TypedDict`](https://docs.python.org/3.8/library/typing.html#typing.TypedDict)? – Georgy Oct 10 '19 at 15:08
  • 2
    Check this post: [Python 3 dictionary with known keys typing](https://stackoverflow.com/questions/44225788/python-3-dictionary-with-known-keys-typing) – Georgy Oct 10 '19 at 15:16
  • Thanks for both suggestions @Georgy. – NoSplitSherlock Oct 10 '19 at 17:37

1 Answers1

2
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:
  ...
peter554
  • 1,248
  • 1
  • 12
  • 24