标签归档:docstring

如何在Python中记录类属性?[关闭]

问题:如何在Python中记录类属性?[关闭]

我正在编写一个轻量级的类,其属性旨在可公开访问,并且有时仅在特定的实例中被覆盖。就此而言,Python语言中没有为类属性或任何类型的属性创建文档字符串的规定。记录这些属性的预期方式和受支持方式是什么?目前,我正在做这种事情:

class Albatross(object):
    """A bird with a flight speed exceeding that of an unladen swallow.

    Attributes:
    """

    flight_speed = 691
    __doc__ += """
        flight_speed (691)
          The maximum speed that such a bird can attain.
    """

    nesting_grounds = "Raymond Luxury-Yacht"
    __doc__ += """
        nesting_grounds ("Raymond Luxury-Yacht")
          The locale where these birds congregate to reproduce.
    """

    def __init__(self, **keyargs):
        """Initialize the Albatross from the keyword arguments."""
        self.__dict__.update(keyargs)

这将导致该类的docstring包含初始的标准docstring部分,以及通过对的扩展分配为每个属性添加的行__doc__

尽管docstring样式指南中似乎并未明确禁止使用这种样式,但也没有提到它是一种选择。这样做的好处是,它提供了一种在定义时连同属性一起记录属性的方法,同时仍然创建了一个可显示的类docstring,并且避免了编写注释以重申该docstring中的信息。我仍然对必须两次写入属性感到恼火。我正在考虑使用文档字符串中值的字符串表示形式来至少避免重复默认值。

这是对特设社区惯例的严重违反吗?可以吗 有没有更好的办法?例如,可以创建一个包含属性值和文档字符串的字典,然后__dict__在类声明的末尾将内容添加到该类和文档字符串中。这样可以减少两次键入属性名称和值的需要。 编辑:我认为,最后一个想法实际上是不可能的,至少没有没有根据数据动态构建整个类的想法,除非有其他原因,否则这似乎是一个糟糕的主意。

我是python的新手,仍然在研究编码风格的细节,因此也欢迎无关的批评。

I’m writing a lightweight class whose attributes are intended to be publicly accessible, and only sometimes overridden in specific instantiations. There’s no provision in the Python language for creating docstrings for class attributes, or any sort of attributes, for that matter. What is the expected and supported way, should there be one, to document these attributes? Currently I’m doing this sort of thing:

class Albatross(object):
    """A bird with a flight speed exceeding that of an unladen swallow.

    Attributes:
    """

    flight_speed = 691
    __doc__ += """
        flight_speed (691)
          The maximum speed that such a bird can attain.
    """

    nesting_grounds = "Raymond Luxury-Yacht"
    __doc__ += """
        nesting_grounds ("Raymond Luxury-Yacht")
          The locale where these birds congregate to reproduce.
    """

    def __init__(self, **keyargs):
        """Initialize the Albatross from the keyword arguments."""
        self.__dict__.update(keyargs)

This will result in the class’s docstring containing the initial standard docstring section, as well as the lines added for each attribute via augmented assignment to __doc__.

Although this style doesn’t seem to be expressly forbidden in the docstring style guidelines, it’s also not mentioned as an option. The advantage here is that it provides a way to document attributes alongside their definitions, while still creating a presentable class docstring, and avoiding having to write comments that reiterate the information from the docstring. I’m still kind of annoyed that I have to actually write the attributes twice; I’m considering using the string representations of the values in the docstring to at least avoid duplication of the default values.

Is this a heinous breach of the ad hoc community conventions? Is it okay? Is there a better way? For example, it’s possible to create a dictionary containing values and docstrings for the attributes and then add the contents to the class __dict__ and docstring towards the end of the class declaration; this would alleviate the need to type the attribute names and values twice. edit: this last idea is, I think, not actually possible, at least not without dynamically building the entire class from data, which seems like a really bad idea unless there’s some other reason to do that.

I’m pretty new to python and still working out the details of coding style, so unrelated critiques are also welcome.


回答 0

为避免混淆:术语property在python中具有特定含义。您所说的是所谓的类属性。由于始终在类中对它们进行操作,因此我发现将它们记录在类的文档字符串中是有意义的。像这样:

class Albatross(object):
    """A bird with a flight speed exceeding that of an unladen swallow.

    Attributes:
        flight_speed     The maximum speed that such a bird can attain.
        nesting_grounds  The locale where these birds congregate to reproduce.
    """
    flight_speed = 691
    nesting_grounds = "Throatwarbler Man Grove"

我认为这比示例中的方法容易得多。如果我确实希望属性值的副本出现在doc字符串中,则可以将它们放在每个属性的描述的旁边或下方。

请记住,在Python中,文档字符串是其文档对象的实际成员,而不仅仅是源代码注释。由于类属性变量本身不是对象而是对象的引用,因此它们无法保存自己的文档字符串。我想您可以为引用中的doc字符串辩护,也许是描述“应该在这里做什么”而不是“实际在这里”,但是我发现在包含类的doc字符串中这样做很容易。

To avoid confusion: the term property has a specific meaning in python. What you’re talking about is what we call class attributes. Since they are always acted upon through their class, I find that it makes sense to document them within the class’ doc string. Something like this:

class Albatross(object):
    """A bird with a flight speed exceeding that of an unladen swallow.

    Attributes:
        flight_speed     The maximum speed that such a bird can attain.
        nesting_grounds  The locale where these birds congregate to reproduce.
    """
    flight_speed = 691
    nesting_grounds = "Throatwarbler Man Grove"

I think that’s a lot easier on the eyes than the approach in your example. If I really wanted a copy of the attribute values to appear in the doc string, I would put them beside or below the description of each attribute.

Keep in mind that in Python, doc strings are actual members of the objects they document, not merely source code annotations. Since class attribute variables are not objects themselves but references to objects, they have no way of holding doc strings of their own. I guess you could make a case for doc strings on references, perhaps to describe “what should go here” instead of “what is actually here”, but I find it easy enough to do that in the containing class doc string.


回答 1

您在“ 什么是文档字符串 ”部分中引用了PEP257:文档字符串约定

Python代码其他地方出现的字符串文字也可以用作文档。它们无法被Python字节码编译器识别,并且不能作为运行时对象属性(即未分配给__doc__)访问,但是软件工具可以提取两种类型的额外docstring:

在模块,类或__init__方法的顶级进行简单赋值后立即出现的字符串文字称为“属性文档字符串”。

这在PEP 258:属性文档字符串中有更详细的说明。正如上面的解释。属性不是可以拥有__doc__的对象,因此它们不会出现在help()或pydoc中。这些文档字符串只能用于生成的文档。

它们在Sphinx中与指令autoattribute一起使用

Sphinx可以在赋值之前的一行上使用注释,或者在赋值之后的特殊注释或定义之后的文档字符串中使用这些注释,这些注释将自动记录在案。

You cite the PEP257: Docstring Conventions, in the section What is a docstring it is stated:

String literals occurring elsewhere in Python code may also act as documentation. They are not recognized by the Python bytecode compiler and are not accessible as runtime object attributes (i.e. not assigned to __doc__), but two types of extra docstrings may be extracted by software tools:

String literals occurring immediately after a simple assignment at the top level of a module, class, or __init__ method are called “attribute docstrings”.

And this is explained in more details in PEP 258: Attribute docstrings. As explains above ʇsәɹoɈ. an attribute is not an object that can own a __doc__ so they won’t appear in help() or pydoc. These docstrings can only be used for generated documentation.

They are used in Sphinx with the directive autoattribute

Sphinx can use comments on a line before an assignment or a special comment following an assignment or a docstring after the definition which will be autodocumented.


回答 2

您可以滥用此属性。属性包含getter,setter,deleter 和docstring。天真的,这会变得很冗长:

class C:
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """Docstring goes here."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

然后,您将拥有一个属于Cx的文档字符串:

In [24]: print(C.x.__doc__)
Docstring goes here.

要对许多属性执行此操作比较麻烦,但是您可以设想一个辅助函数myprop:

def myprop(x, doc):
    def getx(self):
        return getattr(self, '_' + x)

    def setx(self, val):
        setattr(self, '_' + x, val)

    def delx(self):
        delattr(self, '_' + x)

    return property(getx, setx, delx, doc)

class C:
    a = myprop("a", "Hi, I'm A!")
    b = myprop("b", "Hi, I'm B!")

In [44]: c = C()

In [46]: c.b = 42

In [47]: c.b
Out[47]: 42

In [49]: print(C.b.__doc__)
Hi, I'm B!

然后,以交互方式调用Python help将得到:

Help on class C in module __main__:

class C
 |  Data descriptors defined here:
 |  
 |  a
 |      Hi, I'm A!
 |  
 |  b
 |      Hi, I'm B!

我认为这应该是您所追求的。

编辑:现在我意识到,也许我们可以完全避免将第一个参数传递给它myprop,因为内部名称无关紧要。如果后续的调用myprop可以通过某种方式彼此通信,则它可以自动确定一个较长且不太可能的内部属性名称。我敢肯定有实现此目的的方法,但是我不确定他们是否值得。

You could abuse properties to this effect. Properties contain a getter, a setter, a deleter, and a docstring. Naively, this would get very verbose:

class C:
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """Docstring goes here."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

Then you will have a docstring belonging to C.x:

In [24]: print(C.x.__doc__)
Docstring goes here.

To do this for many attributes is cumbersome, but you could envision a helper function myprop:

def myprop(x, doc):
    def getx(self):
        return getattr(self, '_' + x)

    def setx(self, val):
        setattr(self, '_' + x, val)

    def delx(self):
        delattr(self, '_' + x)

    return property(getx, setx, delx, doc)

class C:
    a = myprop("a", "Hi, I'm A!")
    b = myprop("b", "Hi, I'm B!")

In [44]: c = C()

In [46]: c.b = 42

In [47]: c.b
Out[47]: 42

In [49]: print(C.b.__doc__)
Hi, I'm B!

Then, calling Pythons interactive help will give:

Help on class C in module __main__:

class C
 |  Data descriptors defined here:
 |  
 |  a
 |      Hi, I'm A!
 |  
 |  b
 |      Hi, I'm B!

which I think should be pretty much what you’re after.

Edit: I realise now that we can perhaps avoid to need to pass the first argument to myprop at all, because the internal name doesn’t matter. If subsequent calls of myprop can somehow communicate with each other, it could automatically decide upon a long and unlikely internal attribute name. I’m sure there are ways to implement this, but I’m not sure if they’re worth it.


将javadoc用于Python文档[关闭]

问题:将javadoc用于Python文档[关闭]

我目前从Python开始,我有很强的PHP背景,在PHP中,我习惯于javadoc用作文档模板。

我想知道它是否在Python文档中javadoc占有一席之地docstring这里有哪些既定的公约和/或官方指南?

例如,类似这样的内容太复杂,无法适应Python的思维方式,还是我应该尽量简洁一些?

"""
replaces template place holder with values

@param string timestamp     formatted date to display
@param string priority      priority number
@param string priority_name priority name
@param string message       message to display

@return string formatted string
"""

而且,如果我有点过于详尽,我应该改用类似的东西(大多数文档都无法通过该__doc__方法打印)吗?

# replaces template place holder with values
#    
# @param string timestamp     formatted date to display
# @param string priority      priority number
# @param string priority_name priority name
# @param string message       message to display
#    
# @return string formatted string

def format(self, timestamp = '', priority = '', priority_name = '', message = ''):
    """
    replaces template place holder with values
    """
    values = {'%timestamp%' : timestamp,
              '%priorityName%' : priority_name,
              '%priority%' : priority,
              '%message%' : message}

    return self.__pattern.format(**values)

I am currently beginning with Python and I have a strong PHP background and in PHP I have took the habit of using javadoc as a documentation template.

I was wondering if javadoc has its place as docstring documentation in Python. What are the established conventions and/or official guildelines here?

E.g. is something like this too elaborate to fit in the Python mindset or should I try to be as concise as possible?

"""
replaces template place holder with values

@param string timestamp     formatted date to display
@param string priority      priority number
@param string priority_name priority name
@param string message       message to display

@return string formatted string
"""

And if I am a bit too exhaustive should I go with something like this instead (where most of the documentation doesn’t get printed through the __doc__ method)?

# replaces template place holder with values
#    
# @param string timestamp     formatted date to display
# @param string priority      priority number
# @param string priority_name priority name
# @param string message       message to display
#    
# @return string formatted string

def format(self, timestamp = '', priority = '', priority_name = '', message = ''):
    """
    replaces template place holder with values
    """
    values = {'%timestamp%' : timestamp,
              '%priorityName%' : priority_name,
              '%priority%' : priority,
              '%message%' : message}

    return self.__pattern.format(**values)

回答 0

看一下reStructuredText(也称为“ reST”)格式,它是纯文本/文档字符串标记格式,可能是Python世界中最流行的格式。而且,您当然应该看一下Sphinx,它是一种从reStructuredText生成文档的工具(例如用于Python文档本身)。Sphinx允许从代码中的文档字符串中提取文档(请参见sphinx.ext.autodoc),并按照某些约定识别reST 字段列表。这可能已经成为(或正在成为)最流行的方法。

您的示例如下所示:

"""Replaces template placeholder with values.

:param timestamp: formatted date to display
:param priority: priority number
:param priority_name: priority name
:param message: message to display
:returns: formatted string
"""

或扩展了类型信息:

"""Replaces template placeholder 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
"""

Have a look at the reStructuredText (also known as “reST”) format, which is a plaintext/docstring markup format, and probably the most popular in the Python world. And you should certainly look at Sphinx, a tool to generate documentation from reStructuredText (used for eg. the Python documentation itself). Sphinx includes the possibility to extract documentation from the docstrings in your code (see sphinx.ext.autodoc), and recognizes reST field lists following certain conventions. This has probably become (or is becoming) the most popular way to do it.

Your example could look as follows:

"""Replaces template placeholder with values.

:param timestamp: formatted date to display
:param priority: priority number
:param priority_name: priority name
:param message: message to display
:returns: formatted string
"""

Or extended with type information:

"""Replaces template placeholder 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
"""

回答 1

遵循Google Python样式指南。请注意,Sphinx还可以使用Napolean扩展来解析此格式,该扩展将与Sphinx 1.3打包在一起(这也与PEP257兼容):

def func(arg1, arg2):
    """Summary line.

    Extended description of function.

    Args:
        arg1 (int): Description of arg1
        arg2 (str): Description of arg2

    Returns:
        bool: Description of return value

    """
    return True

示例取自上面链接的Napolean文档。

这里是有关所有类型的文档字符串的综合示例。

Follow Google Python Style Guide. Note that Sphinx can also parse this format using the Napolean extension, which will come packaged with Sphinx 1.3 (this is also compatible with PEP257):

def func(arg1, arg2):
    """Summary line.

    Extended description of function.

    Args:
        arg1 (int): Description of arg1
        arg2 (str): Description of arg2

    Returns:
        bool: Description of return value

    """
    return True

Example taken from the Napolean documentation linked above.

A comprehensive example on all types of docstrings here.


回答 2

Python增强建议257中描述了python文档字符串的标准。

适用于您的方法的注释应类似于

def format(...):
    """Return timestamp string with place holders replaced with values.

    Keyword arguments:
    timestamp     -- the format string (default '')
    priority      -- priority number (default '')
    priority_name -- priority name (default '')
    message       -- message to display (default '')
    """

The standard for python documentation strings is described in Python Enhancement Proposal 257.

The appropriate comment for your method would be something like

def format(...):
    """Return timestamp string with place holders replaced with values.

    Keyword arguments:
    timestamp     -- the format string (default '')
    priority      -- priority number (default '')
    priority_name -- priority name (default '')
    message       -- message to display (default '')
    """

回答 3

看一下Documenting Python,这是“针对Python文档的作者和潜在作者的页面”。

简而言之,reStructuredText是用于记录Python本身的东西。开发人员指南包含reST入门,样式指南以及有关编写良好文档的一般建议。

Take a look at Documenting Python, a page “aimed at authors and potential authors of documentation for Python.”

In short, reStructuredText is what’s used for documenting Python itself. The developer’s guide contains a reST primer, style guide, and general advice for writing good documentation.


标准的Python文档字符串格式是什么?[关闭]

问题:标准的Python文档字符串格式是什么?[关闭]

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

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


回答 0

格式

可以按照其他文章所示的几种格式编写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有自己常用的格式。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项目生成文档字符串,或者将现有文档字符串(可以混合多种格式)从一种格式转换为另一种格式。

注意:这些示例摘自Pyment文档

Formats

Python docstrings can be written following several formats as the other posts showed. However the default Sphinx docstring format was not mentioned and is based on reStructuredText (reST). You can get some information about the main formats in this blog post.

Note that the reST is recommended by the PEP 287

There follows the main used formats for docstrings.

– Epytext

Historically a javadoc like style was prevalent, so it was taken as a base for Epydoc (with the called Epytext format) to generate documentation.

Example:

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

Nowadays, the probably more prevalent format is the reStructuredText (reST) format that is used by Sphinx to generate documentation. Note: it is used by default in JetBrains PyCharm (type triple quotes after defining a method and hit enter). It is also used by default as output format in Pyment.

Example:

"""
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 has their own format that is often used. It also can be interpreted by Sphinx (ie. using Napoleon plugin).

Example:

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

Even more examples

– Numpydoc

Note that Numpy recommend to follow their own numpydoc based on Google format and usable by 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
"""

Converting/Generating

It is possible to use a tool like Pyment to automatically generate docstrings to a Python project not yet documented, or to convert existing docstrings (can be mixing several formats) from a format to an other one.

Note: The examples are taken from the Pyment documentation


回答 1

谷歌的风格指南中包含一个优秀的Python风格指南。它包括可读文档字符串语法的约定,约定比PEP-257提供更好的指导。例如:

def square_root(n):
    """Calculate the square root of a number.

    Args:
        n: the number to get the square root of.
    Returns:
        the square root of n.
    Raises:
        TypeError: if n is not a number.
        ValueError: if n is negative.

    """
    pass

我想将此扩展为在参数中也包含类型信息,如本Sphinx文档教程中所述。例如:

def add_value(self, value):
    """Add a new value.

       Args:
           value (str): the value to add.
    """
    pass

The Google style guide contains an excellent Python style guide. It includes conventions for readable docstring syntax that offers better guidance than PEP-257. For example:

def square_root(n):
    """Calculate the square root of a number.

    Args:
        n: the number to get the square root of.
    Returns:
        the square root of n.
    Raises:
        TypeError: if n is not a number.
        ValueError: if n is negative.

    """
    pass

I like to extend this to also include type information in the arguments, as described in this Sphinx documentation tutorial. For example:

def add_value(self, value):
    """Add a new value.

       Args:
           value (str): the value to add.
    """
    pass

回答 2

PEP-257中的文档字符串约定比PEP-8更为详细。

但是,文档字符串似乎比其他代码区域更具个性。不同的项目将有自己的标准。

我倾向于总是包含docstrings,因为它们倾向于演示如何使用该函数以及该函数的执行速度非常快。

无论字符串的长度如何,我都希望保持一致。我喜欢缩进和间距一致时的代码外观。这意味着,我使用:

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

过度:

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

并倾向于在较长的文档字符串中省略第一行的注释:

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

意思是我发现像这样开始的文档字符串很乱。

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

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

回答 3

显然没有人提到它:您还可以使用Numpy Docstring Standard。它在科学界被广泛使用。

用于解析Google样式文档字符串的Napolean狮身人面像扩展名(在@Nathan的答案中建议)也支持Numpy样式文档字符串,并对两者进行简短的比较

最后一个基本示例给出了它的外观:

def func(arg1, arg2):
    """Summary line.

    Extended description of function.

    Parameters
    ----------
    arg1 : int
        Description of arg1
    arg2 : str
        Description of arg2

    Returns
    -------
    bool
        Description of return value

    See Also
    --------
    otherfunc : some related other function

    Examples
    --------
    These are written in doctest format, and should illustrate how to
    use the function.

    >>> a=[1,2,3]
    >>> print [x + 3 for x in a]
    [4, 5, 6]
    """
    return True

As apparantly no one mentioned it: you can also use the Numpy Docstring Standard. It is widely used in the scientific community.

The Napolean sphinx extension to parse Google-style docstrings (recommended in the answer of @Nathan) also supports Numpy-style docstring, and makes a short comparison of both.

And last a basic example to give an idea how it looks like:

def func(arg1, arg2):
    """Summary line.

    Extended description of function.

    Parameters
    ----------
    arg1 : int
        Description of arg1
    arg2 : str
        Description of arg2

    Returns
    -------
    bool
        Description of return value

    See Also
    --------
    otherfunc : some related other function

    Examples
    --------
    These are written in doctest format, and should illustrate how to
    use the function.

    >>> a=[1,2,3]
    >>> print [x + 3 for x in a]
    [4, 5, 6]
    """
    return True

回答 4

PEP-8是官方的python编码标准。它包含有关文档字符串的部分,该部分引用了PEP- 257-文档字符串的完整规范。

PEP-8 is the official python coding standard. It contains a section on docstrings, which refers to PEP-257 — a complete specification for docstrings.


回答 5

是Python;一切顺利。考虑如何发布您的文档。除了您的源代码读者以外,文档字符串是不可见的。

人们真的很喜欢浏览和搜索网络上的文档。为此,请使用文档工具Sphinx。这是记录Python项目的实际标准。该产品非常漂亮-请访问https://python-guide.readthedocs.org/en/latest/。“ 阅读文档 ”网站将免费托管您的文档。

It’s Python; anything goes. Consider how to publish your documentation. Docstrings are invisible except to readers of your source code.

People really like to browse and search documentation on the web. To achieve that, use the documentation tool Sphinx. It’s the de-facto standard for documenting Python projects. The product is beautiful – take a look at https://python-guide.readthedocs.org/en/latest/ . The website Read the Docs will host your docs for free.


回答 6

我建议使用Vladimir Keleshev的pep257 Python程序根据PEP-257Numpy Docstring Standard检查您的文档字符串,以描述参数,返回值等。

pep257将报告您与标准的差异,称为pylint和pep8。

I suggest using Vladimir Keleshev’s pep257 Python program to check your docstrings against PEP-257 and the Numpy Docstring Standard for describing parameters, returns, etc.

pep257 will report divergence you make from the standard and is called like pylint and pep8.