27

I'm trying to use reST-style docstrings, i.e.

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

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

Is there a standard way to document yields? I looked at http://www.sphinx-doc.org/en/master/usage/restructuredtext/domains.html#info-field-lists, a-la this question [ https://stackoverflow.com/questions/5334531/python-documentation-standard-for-docstring ], but no luck. I'm imagining something like,

:yields: transformed bars
:yield type: Baz
bad_coder
  • 11,289
  • 20
  • 44
  • 72
gatoatigrado
  • 16,580
  • 18
  • 81
  • 143
  • 1
    Close to [Docstring tag for 'yield' keyword](http://stackoverflow.com/questions/7652540/docstring-tag-for-yield-keyword?rq=1). – alecxe Jun 27 '14 at 22:19
  • I don't know reST, but my guess would be that you document it the way you'd document any other "returns an iterator" function. The use of `yield` is an implementation detail. – user2357112 Jun 27 '14 at 22:20
  • yeah, I know the other question is similar, I want a reST-specific answer, thanks! – gatoatigrado Jun 27 '14 at 23:29

2 Answers2

12

Python 3.5 Iterator[] annotation

They offer a standardized Iterator[] syntax for this as documented at: https://docs.python.org/3/library/typing.html#typing.Generator

Before Python 3, I recommend that you use this syntax to make it easier to port later on:

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

And after Python 3, use https://pypi.python.org/pypi/sphinx-autodoc-annotation with syntax:

from typing import Iterator
def f() -> Iterator[SomeClass]:
    yield SomeClass()
Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
4

I have reviewed the other answer and it doesn't in my opinion answer the question.

The way to document a generator, although not the best, is by using :return as in the rest of the docs. Use the description to give notice that it is a generator.

Yields from Google/Numpy style docs convert yields to return clauses.

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

txomon
  • 642
  • 1
  • 6
  • 21