Here's our idea of what the Docstrings for those functions should look like.
Yours may be different, and that's fine. There's no right or wrong here, and any documentation is usually better than no documentation.
Hopefully, these examples will give you ideas about the sort of information you should include in your Docstrings, and the sorts of things you should think about when writing the documentation.
When we wrote the multiply function, the aim was just to multiply 2 numbers and return the product. After writing it, we realised that the first argument could be any sequence type. That's worth putting in the Docstring.
But note that once you do put something in the Docstring, it becomes part of the documented behaviour of your code.
If we make changes to this function, we'll need to make sure that it still works if the first argument is a sequence, rather than a number.
If it doesn't, someone who trusted our documentation, and used the function to multiply sequences, will find their code breaks when we release the updated version of the function.
That's not a very nice thing to do to another programmer.
If you think that you might change the multiply function so that it no longer works with sequences, then don't put that comment in the Docstring.
Ok, here are the functions with the Docstrings that we produced:
def multiply(x, y):
"""
Multiply 2 numbers.
Although this function is intended to multiply 2 numbers,
you can also use it to multiply a sequence. If you pass
a string, for example, as the first argument, you'll get
the string repeated `y` times as the returned value.
:param x: The first number to multiply.
:param y: The number to multiply `x` by.
:return: The product of `x` and `y`.
"""
result = x * y
return result
def is_palindrome(string):
"""
Check if a string is a palindrome.
A palindrome is a string that reads the same forwards as backwards.
:param string: The string to check.
:return: True if `string` is a palindrome, False otherwise.
"""
return string[::-1].casefold() == string.casefold()
def palindrome_sentence(sentence):
"""
Check if a sentence is a palindrome.
The function ignores whitespace, capitalisation and
punctuation in the sentence.
:param sentence: The sentence to check.
:return: True if `sentence` is a palindrome, False otherwise.
"""
string = ""
for char in sentence:
if char.isalnum():
string += char
return is_palindrome(string)You'll notice that we took the opportunity to delete some of the commented out code that wasn't being used. That's something you should do, when releasing your functions for general use.
We also removed the diagnostic print statement, from the palindrome_sentence function.
One other thing you'll notice, if you check these Docstrings, is that backticks display as backticks, when used in the :param and :return text.
That's fine. People reading Docstrings soon get used to names being enclosed in backticks, if the font isn't changed.