Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Comparing Common Python Docstring Styles

Resource mentioned in this lesson: Python’s doctest: Document and Test Your Code at Once

00:00 In this lesson, you’ll be exploring three common styles for writing Python docstrings, reStructuredText docstrings, Google-style docstrings, and NumPy-style docstrings.

00:11 Let’s go! Your first example is reStructuredText style. And since reStructuredText is a bit of a mouthful, it’s often referred to as RST, or ReST. ReST is a lightweight markup language used for writing structured plain text, and it’s the default style for docstrings in Python.

00:29 Details are actually laid out in another PEP—PEP 287—and it’s also the default for tools like Sphinx that generate documentation from docstrings. Take a look at this important spell-casting function and its docstring.

00:42 def cast_spell() parameters: wand, incantation, and target, which defaults to None. Cast a magical spell using a wand and incantation.

00:51 This function simulates casting a spell with no target specified. It is cast into the void. param wand: the wand used to do the spell-casting deed. type wand: str.

01:03 param incantation: the word said to activate the magic. type incantation: str. param target: the object or person the spell is directed at. Optional. Type target: str.

01:16 Optional. Return: A string describing the result of the spell. :rtype: str.

01:23 Raises ValueError: if incantation is unknown or the wand fails to work. Valid incantations: the list of strings lumos, alohomora, and expelliarmus.

01:34 If not wand, raise ValueError with the message, "You can't cast spells without a wand." If incantation not in valid_incantations, raise ValueError: "Incantation not recognized." And if target, return the f-string: "{incantation} hits {target} with magic speed." Finally, return the f-string: "{incantation} is cast into the void.

01:56 ...sparkles shimmer faintly."

01:59 So what are the requirements for this ReST-style? Parameters should be listed, as well as their types.

02:06 You can see that the wand parameter is listed with its type str, incantation, also a str, and target, again a str, this time optional.

02:17 Their description should briefly explain their purpose in the behavior of the function.

02:22 The return value should also be explained, as well as its type. And any errors that may be raised by the function should also be listed. If needed, you can add headers, lists, and even links to further improve the structure.

02:35 But this example here is pretty much all you’ll need for systems like Sphinx or docutils to understand your docstring. And while, on its face, reStructuredText can seem a little cumbersome, it’s definitely worth the increased complexity, especially if you’re interested in generating HTML or PDF documentation from your docstrings.

02:54 Moving on to Google-style docstrings, these are a more easily human-readable style of docstring. This style became popular at Google as a result of them having large Python codebases throughout the company, and slowly permeated the rest of the Python community.

03:09 Examine this function and its docstring. This is a function you would definitely need to call before starting a new year at your school of warlockery and macraft.

03:16 def get_magic_items() with the parameters user_id and include_potions, defaulting to False. Retrieve a list of magical items for a specific user. List of args: user_id (int): The ID of the user whose items should be retrieved.

03:34 include_potions (bool, optional): A Boolean optional whether to include potions, list of returns: a list[str], a list of item names associated with the user.

03:46 items equals the list of strings wand, cloak, and crystal ball. If include_potions, items.extend() the list healing potion and invisibility potion.

03:56 Finally, return items.

03:58 What’s important here is that you include the lists: Args for parameters and their types and descriptions, Returns for return values and their types and descriptions; and, if applicable, Raises for any exceptions that may be raised by the function.

04:13 It’s a pretty straightforward format without too much fuss.

04:17 And last but not least, we look at the NumPy style. This is the predominant style found in the scientific Python community in libraries like NumPy, pandas, SciPy, and others.

04:29 Here’s how you might use a NumPy-styled docstring to document a function for brewing mystical concoctions. def brew_potion() with the parameters ingredients and heat_level. Brew a potion using selective ingredients and heat. Parameters, underlined with dashes.

04:45 ingredients: a list[str], a list of magical ingredients, heat level, an integer, the intensity of the heat used for brewing. Returns, again, underlined by dashes.

04:58 A str: a description of the brewed potion, and the functionality: return an f-string, "An elixir of {', '.join(ingredients)}, heated at {heat_level}."

05:09 The biggest apparent difference here is the headers underlined by dashes, emphasizing the parameters and returns. And because this is the preferred style in scientific Python circles, there are usually headers for usage examples and even academic references.

05:23 So if your work is scientific in nature, data-related, or depends heavily on similar such libraries, the NumPy style would be a great choice for your docstrings.

05:35 And though we didn’t cover it here, there’s one more style of writing docstrings you might find interesting: the doctest style, where your docstrings can be used to implement testing.

05:44 If you’re interested, check out “Python’s doctest: Document and Test Your Code at Once”.

05:50 Alright, we covered the major docstring formats, but did you notice each docstring was for a function? Are you maybe wondering what you should do differently when writing docstrings for modules or classes?

06:01 Well, you don’t need to wonder. Just watch the next lesson.

Become a Member to join the conversation.