标准的Python文档字符串格式是什么?

发布于 2021-02-02 23:09:36

我已经看到了几种用Python编写文档字符串的不同样式,是否有正式的或“同意的”样式?

关注者
0
被浏览
68
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    格式

    可以按照其他文章所示的几种格式编写Python文档字符串。但是,未提到默认的Sphinx文档字符串格式,该格式基于reStructuredText(reST)。你可以在此博客文章中获得有关主要格式的一些信息。

    请注意,reST是PEP 287推荐的

    以下是文档字符串的主要使用格式。

    -Epytext

    从历史上看,像Javadoc这样的样式很普遍,因此它被视为Epydoc(具有所谓的Epytext格式)生成文档的基础。

    例:

    """
    This is a javadoc style.
    
    @param param1: this is a first param
    @param param2: this is a second param
    @return: this is a description of what is returned
    @raise keyError: raises an exception
    """
    

    -reST

    如今,可能更流行的格式是Sphinx用于生成文档的reStructuredText(reST)格式。注意:它在JetBrains PyCharm中默认使用(在定义方法后键入三引号并按Enter键)。默认情况下,它也用作Pyment中的输出格式。

    例:

    """
    This is a reST style.
    
    :param param1: this is a first param
    :param param2: this is a second param
    :returns: this is a description of what is returned
    :raises keyError: raises an exception
    """
    
    • Google

    Google有自己常用的格式。Sphinx也可以解释它(即使用Napoleon插件)。

    例:

    """
    This is an example of Google style.
    
    Args:
        param1: This is the first param.
        param2: This is a second param.
    
    Returns:
        This is a description of what is returned.
    
    Raises:
        KeyError: Raises an exception.
    """
    

    甚至更多的例子

    -Numpydoc
    请注意,Numpy建议根据Google格式使用自己的numpydoc,并且Sphinx可以使用。

    """
    My numpydoc description of a kind
    of very exhautive numpydoc format docstring.
    
    Parameters
    ----------
    first : array_like
        the 1st param name `first`
    second :
        the 2nd param
    third : {'value', 'other'}, optional
        the 3rd param, by default 'value'
    
    Returns
    -------
    string
        a value in a string
    
    Raises
    ------
    KeyError
        when a key error
    OtherError
        when an other error
    """
    

    转换/生成

    可以使用诸如Pyment之类的工具自动为尚未记录的Python项目生成文档字符串,或将现有文档字符串(可以混合多种格式)从一种格式转换为另一种格式。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看