有没有一种方法可以描述/类型提示函数参数的内容?

4

我正在尝试学习如何更好地记录我的代码。仅描述一个函数并暗示它接收“dict”似乎会让任何未来的读者缺乏信息。

这种做法常见吗?还是我在阅读该主题时错过了其他方法?

    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
        """

编辑:在盲目地称其为重复问题之前,请认真阅读一下问题。我的问题已经显示出我知道什么是类型提示,我正在寻找关于处理参数中嵌套对象时类型提示的工作方式的非常特定部分的答案。


1
可能是Python 3.5中的类型提示是什么的重复问题。 - Georgy
@Georgy 我知道一般情况下类型提示是什么,但是那个链接里并没有回答我这里所问的问题。我似乎找不到任何关于这个特定主题的资料。更明确地说,我对所谓的“嵌套类型提示”感兴趣。 - NoSplitSherlock
3
你是否在寻找一个 TypedDict(https://docs.python.org/3.8/library/typing.html#typing.TypedDict)? - Georgy
2
请查看此帖子:Python 3 dictionary with known keys typing - Georgy
感谢您的两个建议,@Georgy。 - NoSplitSherlock
1个回答

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):
  ...
  • 为了更好地记录代码,您应该添加返回类型。
def add_control(self, ctrl_data: CtrlData) -> TReturn:
  ...
  • 您还可以更改函数签名,让调用者对字典进行解包。我认为当您只有少量参数时,这种方式更清晰。
def add_control(
  self,
  name: str,
  channel: int,
  control_channel_id: int,
  default_position: int
  ) -> TReturn:
  ...

1
谢谢两位的回答。这为我提供了两种不同原因的解决方法。 - NoSplitSherlock

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接