什么是标准的Python文档字符串格式? [英] What is the standard Python docstring format?

查看:173
本文介绍了什么是标准的Python文档字符串格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解决方案

我已经在Python中看到了几种不同的写文档字符串样式,

文档字符串惯例位于 PEP-257 中,比PEP-8详细得多。



然而,docstrings似乎比其他代码领域更加个人化。不同的项目将有自己的标准。



我倾向于总是包含docstrings,因为它们往往演示如何使用函数及其操作非常快。



我喜欢保持一致,不管字符串的长度。我喜欢在缩进和间距一致时如何编写代码。这意味着我使用:

  def sq(n):

of n。

return n * n

/ p>

  def sq(n):
返回n的平方
return n * n

并且倾向于对更长的文档字符串的第一行进行注释:

  def sq(n):

返回n的平方,接受所有数字类型:

>>> sq(10)
100

>>> sq(10.434)
108.86835599999999

当输入无效时引发TypeError:

>>> sq(4 *'435')
回溯(最近一次调用)

TypeError:不能将序列乘以类型'str'的非int类型


return n * n



含义我发现文档字符串开始这样乱码。

 code> def sq(n):
返回平方结果。
...


I have seen a few different styles of writing docstrings in Python, is there an official or "agreed-upon" style?

解决方案

Docstring conventions are in PEP-257 with much more detail than PEP-8.

However, docstrings seem to be far more personal than other areas of code. Different projects will have their own standard.

I tend to always include docstrings, because they tend to demonstrate how to use the function and what it does very quickly.

I prefer to keep things consistent, regardless of the length of the string. I like how to code looks when indentation and spacing are consistent. That means, I use:

def sq(n):
    """
    Return the square of n. 
    """
    return n * n

Over:

def sq(n):
    """Returns the square of n."""
    return n * n

And tend to leave off commenting on the first line in longer docstrings:

def sq(n):
    """
    Return the square of n, accepting all numeric types:

    >>> sq(10)
    100

    >>> sq(10.434)
    108.86835599999999

    Raises a TypeError when input is invalid:

    >>> sq(4*'435')
    Traceback (most recent call last):
      ...
    TypeError: can't multiply sequence by non-int of type 'str'

    """
    return n*n

Meaning I find docstrings that start like this to be messy.

def sq(n):
    """Return the squared result. 
    ...

这篇关于什么是标准的Python文档字符串格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆