Writing class and method function docstrings

A class will often contain a number of elements, including attributes and method functions. A stateful class may also have a relatively complex API. Objects will be created, undergo changes in state, and possibly be garbage-collected at the end of their lives. We might want to describe some (or all) of these state changes in the class docstring or the method function docstrings.

We'll use the field list technique to document the class variables in the overall class docstring. This will generally focus on using the :ivar variable:, :cvar variable:, and :var variable: field list items.

Each individual method function will also use field lists to define the parameters and return the values and exceptions raised by each method function. Here's how we might start to write a class with docstrings for the class and method functions:

class Card:
"""
Definition of a numeric rank playing card.
Subclasses will define :py:class:`FaceCard` and :py:class:`AceCard`.

:ivar rank: int rank of the card
:ivar suit: Suit suit of the card
:ivar hard: int Hard point total for a card
:ivar soft: int Soft total; same as hard for all cards except Aces.
"""

def __init__(
self, rank: int, suit: Suit, hard: int, soft: Optional[int] = None
) -> None:
"""Define the values for this card.

:param rank: Numeric rank in the range 1-13.
:param suit: Suit object from :class:`Suits`
:param hard: Hard point total (or 10 for FaceCard or 1 for AceCard)
:param soft: The soft total for AceCard, otherwise defaults to hard.
"""
self.rank = rank
self.suit = suit
self.hard = hard
self.soft = soft if soft is not None else hard

def __str__(self) -> str:
return f"{self.rank}{self.suit}"

def __repr__(self) -> str:
return f"{self.__class__.__name__}(rank={self.rank}, suit={self.suit})"

When we include this kind of RST markup in the docstring, then a tool such as Sphinx can format very nice-looking HTML output. We've provided you with both class-level documentation of the instance variables as well as method-level documentation of the parameters to one of the method functions.

This example uses the text :py:class:`Card` to generate a reference to the class card. The role name in this markup is a complex-looking :py:class: to help distinguish the Python language domain. In complex projects, there may be multiple language domains, and the role names can reflect the variety of domains.

When we look at this class with help(Card), the RST markup will be visible. It's not too objectionable, as it's semantically meaningful. This points out a balance that we may need to strike between the help() text and the Sphinx documents.

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

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