【问题标题】:Python: Standard way to denote return and parameter typesPython:表示返回和参数类型的标准方法
【发布时间】:2014-07-27 13:40:08
【问题描述】:

是否有一种标准的 Pythonic 方式来表示函数的参数类型和返回类型?

我正在寻找的符号是:

  • help() 可识别
  • IDE 可识别
  • (最好)在 PEP 中描述

我见过一些例子,比如this reSt syntax:

"""replaces template place holder with values

:param timestamp: formatted date to display
:type timestamp: str or unicode
:param priority: priority number
:type priority: str or unicode
:param priority_name: priority name
:type priority_name: str or unicode
:param message: message to display
:type message: str or unicode
:returns: formatted string
:rtype: str or unicode
"""

但是,我不确定这种格式的官方/支持程度如何。

【问题讨论】:

    标签: python python-2.7 types return-type docstring


    【解决方案1】:

    主要有 3/4 格式竞争 Python 文档字符串。请参阅this tuto 以获得概述。 较旧的格式(现已停产)是基于 Javadoc 样式的 Epydoc 的 Epytext。可能更流行的是 Sphinx 格式的 reStructuredText (reST)Google 样式也很常用。当然还有受 Google 风格启发的 Numpydoc

    关于什么应该是官方/标准方式,您可以参考this topic

    每种格式都有自己的方式来表示参数类型和返回类型。以下是一些例子:

    - Epytext / Javadoc

    """
    @param param1: Description of param1
    @type param1: type of param1
    
    @return: description of returned value
    @rtype: type of returned value
    """
    

    - 恢复

    """
    :param param1: Description of param1
    :type param1: type of param1
    
    :return: description of returned value
    :rtype: type of returned value
    """
    

    - 谷歌

    """
    Args:
      param1(int): Description of parameter `param1`.
      param2(str, optional): Description of a parameter. Defaults to None.
    
    Returns:
      bool: True or False depending on the result.
    """
    

    - Numpydoc

    """
    Parameters
    ----------
    param1 : int
        Description of parameter `param1`.
    param2 : {'value1', 'value2'}
        Description of a parameter with two possible values.
    
    Returns
    -------
    int
        Description of the returned value
    """
    

    转换

    请注意,如果您没有文档字符串,或者您想为您的 Python 项目更改文档字符串格式,您可以使用Pyment

    【讨论】:

    • 我使用并投票支持 numpydoc 约定:它更具可读性。
    【解决方案2】:

    AFAIK,没有 PEP 对此进行描述; PEP257 是关于文档字符串的,但实际上非常少(stdlib 文档字符串很少像你的那样精确)。

    这两个相互竞争的标准是您已经找到的,在 Sphinx 中实现的标准,以及更详细(但也更具可读性)的 NumPy convention,在 Sphinx 的 numpydoc 扩展中实现。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-30
      • 2017-01-07
      • 2012-12-21
      • 2012-10-31
      • 1970-01-01
      • 1970-01-01
      • 2018-01-16
      相关资源
      最近更新 更多