2014-06-27 32 views
14

我试图使用REST风格的文档字符串,即是否有一个Sphinx reST Python文档字段的产量?

def foo(bar): 
    """a method that takes a bar 

    :param bar: a Bar instance 
    :type bar: Bar 

是否有记录yields一个标准的方式?我看着http://sphinx-doc.org/domains.html#info-field-lists,a-la这个问题[Using javadoc for Python documentation],但没有运气。我想像的是,

:yields: transformed bars 
    :yield type: Baz 

谢谢!

+1

关闭到[文档字符串标签关于 '产量' 关键字(http://stackoverflow.com/questions/7652540/docstring-tag-for-yield-keyword ?RQ = 1)。 – alecxe

+0

我不知道reST,但我的猜测是你会按照你记录任何其他“返回迭代器”函数的方式记录它。 yield的使用是一个实现细节。 – user2357112

+0

是的,我知道其他问题是类似的,我想要一个特定于reST的答案,谢谢! – gatoatigrado

回答

1

Google python style guide说:

精细。在 生成器函数的文档字符串中使用“Yields:”而不是“Returns:”。

来自实例here采取:

def example_generator(n): 
    """Generators have a ``Yields`` section instead of a ``Returns`` section. 

    Args: 
     n (int): The upper limit of the range to generate, from 0 to `n` - 1 

    Yields: 
     int: The next number in the range of 0 to `n` - 1 

    Examples: 
     Examples should be written in doctest format, and should illustrate how 
     to use the function. 

     >>> print [i for i in example_generator(4)] 
     [0, 1, 2, 3] 

    """ 
    for i in range(n): 
     yield i 

请注意,这不是一个官方的Python编程风格指南。

如果你打算在conf.py将它添加到的extensions列表使用Yields你需要利用sphinxcontrib-napoleon扩展:

extensions = ['...', ..., 'sphinxcontrib.napoleon'] 

sphinxcontrib-napoleon认识Yields关键字among others上的文档字符串预处理步骤:

拿破仑是一个狮身人面像的扩展,使狮身人面像解析NumPy 和谷歌风格文档字符串 - 汗学院推荐的风格。

拿破仑是一个预处理器,它分析与NumPy和谷歌的风格 文档字符串,并把它们转换成新结构化前的狮身人面像 试图分析它们。这发生在中间步骤,而 Sphinx正在处理文档,所以它不会修改任何 实际源代码文件中的文档字符串。


我个人认为,使用Returns:是非常好的,因为一个generator基本上是function的一个特例。

+1

谢谢,但我认为我们现在正在使用reST-y的东西。我喜欢当你没有单一标记类型时它们更加明确一些,例如':param future:[asynchronous] HTTP future',':type future:() - > HTTPResponse'。 – gatoatigrado

+1

@ gatoatigrado是的,但谷歌和numpy docstring实际上使文档更具可读性。抱歉没有专门回答reST。 – alecxe

0

我已经回顾了其他答案,它并没有在我看来回答这个问题。

虽然不是最好的文档生成器的方式是通过使用:return在文档的其余部分。使用描述来通知它是一个生成器。

来自Google/Numpy风格文档的收益将收益率转换为返回子句。

https://bitbucket.org/RobRuana/sphinx-contrib/src/a06ae33f1c70322c271a97133169d96a5ce1a6c2/napoleon/sphinxcontrib/napoleon/docstring.py?at=default&fileviewer=file-view-default#docstring.py-678:680

3

迭代器[]

Python 3的注解提供一个标准化的Iterator[]语法这是在记载:https://docs.python.org/3/library/typing.html#typing.Generator

的Python 3之前,我建议你使用这个语法,使后来更容易移植:

from typing import List 
def f(): 
    """ 
    :rtype: Iterator[:class:`SomeClass`] 
    """ 
    yield SomeClass() 

和Python 3后,使用与https://pypi.python.org/pypi/sphinx-autodoc-annotation语法:

from typing import Iterator 
def f() -> Iterator[SomeClass]: 
    yield SomeClass() 
相关问题