[Tutor] Questions about the formatting of docstrings
steve at pearwood.info
Fri Jul 27 01:49:31 EDT 2018
On Thu, Jul 26, 2018 at 11:34:11PM -0500, boB Stepp wrote:
> I am near the end of reading "Documenting Python Code: A Complete
> Guide" by James Mertz, found at
> https://realpython.com/documenting-python-code/ This has led me to a
> few questions:
> (1) The author claims that reStructuredText is the official Python
> documentation standard. Is this true? If yes, is this something I
> should be doing for my own projects?
Yes, it is true. If you write documentation for the Python standard
library, they are supposed to be in ReST. Docstrings you read in
the interactive interpreter often aren't, but the documentation you read
on the web page has all been automatically generated from ReST text
As for your own projects... *shrug*. Are you planning to automatically
build richly formatted PDF and HTML files from plain text documentation?
If not, I wouldn't worry too much.
On the other hand, if your documentation will benefit from things
* lists of items
* with bullets
a concise explanation of the meaning of a word
then you're probably already using something close to ReST.
> (2) How would type hints work with this reStructuredText formatting?
Before Python 3 introduced syntax for type hints:
def func(arg: int) -> float:
there were a number of de facto conventions for coding that information
into the function doc string. Being plain text, the human reader can
simply read it, but being a standard format, people can write tools to
extract that information and process it.
Well I say standard format, but in fact there were a number of slightly
different competing formats.
> In part of the author's reStructuredText example he has:
> :param file_loc: The file location of the spreadsheet
> :type file_loc: str
As far as I remember, that's not part of standard ReST, but an extension
used by the Sphinx restructured text tool. I don't know what it does
with that information, but being a known format, any tool can parse the
docstring, extract out the parameters and their types, and generate
documentation, do type checking (either statically or dynamically) or
whatever else you want to do.
> It seems to me that if type hinting is being used, then the ":type"
> info is redundant, so I wonder if special provision is made for
> avoiding this redundancy when using type hinting?
No. You can use one, or the other, or both, or neither, whatever takes
I expect that as Python 2 fades away, it will eventually become common
practice to document types using a type hint rather than in the
docstring and people will simply stop writing things like ":type
file_loc: str" in favour of using def func(file_loc: str).
More information about the Tutor