Writing function docstrings

A function docstring can be formatted using field lists to define the parameters and return the values and raised exceptions. Here's an example of a function that includes a docstring:


def card(rank: int, suit: Suit) -> Card:
"""
Create a :py:class:`Card` instance from rank and suit.

:param suit: Suit object
:param rank: Numeric rank in the range 1-13
:returns: :py:class:`Card` instance
:raises TypeError: rank out of range

>>> from Chapter_20.ch20_ex1 import card
>>> str(card(3, Suit.Heart))
'3♥'
>>> str(card(1, Suit.Heart))
'A♥'
"""
if rank == 1:
return AceCard(rank, suit, 1, 11)
elif 2 <= rank < 11:
return Card(rank, suit, rank)
elif 11 <= rank < 14:
return FaceCard(rank, suit, 10)
else:
raise TypeError

The docstring for this function includes parameter definitions, return values, and the raised exceptions. There are four individual field list items that formalize the API. We've included a doctest sequence as well. When we document this module in Sphinx, we'll get very nice-looking HTML output. Additionally, we can use the doctest tool to confirm that the function matches the simple test case.

Sphinx will expand the type hints slightly. The preceding code uses the source, card(rank: int, suit: Suit) -> Card. This will be expanded to ch20_ex1.card(rank: int, suit: ch20_ex1.Suit) -> ch20_ex1.Card in the HTML page that's created by Sphinx. The class names have a prefix added to help readers understand the software.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset