Docstring
Introduction
In programming, a documentation string is a string literal specified in the source code that is used, like a comment, for
documenting a particular segment of code.
Unlike ordinary source code comments or even specially formatted comments such as docblocks, docstrings are not removed from
the source tree when it is parsed and are preserved throughout the whole run time of the program.
This allows the programmer to inspect these comments at run time, for example as an interactive help system or as metadata.
It was apparently first introduced in the original implementation of Emacs TECO.
Languages that support docstrings include
Python
(see
PEP 257
)
, Lisp, Elixir, Clojure, Gherkin, Julia and Haskell.
Examples
First you can describe what the function does, then list the parameters and the return value.
For example,
PyCharm
suggests using the term param that is
parameters
and I believe that this is correct.
def sum(first: float, second: float) -> float: """ Adds two float values :param first: :param second: :return: first + second """ return(first + second)
Some authors, for example on Pluralsight use the term Args, that is arguments and I consider this incorrect.
"""Retrieve and print words from a URL. Usage: python3 words.py <URL> """ import sys from urllib.request import urlopen def fetch_words(url): """Fetch a list of words from a URL. Args: url: The URL of a UTF-8 text document. Returns: A list of strings containing the words from the document """ # PEP 257 # story = urlopen("http://sixty-north.com/c/t.txt") story = urlopen(url) story_words = [] for line in story: line_words = line.decode("utf8").split() for word in line_words: story_words.append(word) story.close() return story_words def print_items(story_words): """Print items one per line. Args: An iterable series of printable items. """ for word in story_words: print(word) def main(url): words = fetch_words(url) print_items(words) if __name__ == "__main__": main(sys.argv[1])
The docstring we have created will look good in the help() output
Learning help
➭ python
Python 3.9.5 (default, Jun 15 2021, 15:30:04) [GCC 9.3.0] on linux Type "help", "copyright", "credits" or "license" for more information.
>>> import words
>>> help(words)
Help on module words: NAME words - Retrieve and print words from a URL. DESCRIPTION Usage: python3 words.py <URL> FUNCTIONS fetch_words(url) Fetch a list of words from a URL. Args: url: The URL of a UTF-8 text document. Returns: A list of strings containing the words from the document main(url) print_items(story_words) Print items one per line. Args: An iterable series of printable items. FILE /home/andrei/python/words.py
Article author: Andrei Olegovich