Lesson 5
Writing Reusable and Self-explanatory Programs
Chapter 7: Style conventions for functions
Documentation strings
Now, have you been commenting your code? 😀
It will also be good practice to document your functions too. It should explain:
- What the function does
- What parameters are available as arguments, and what type would you expect them to be
- What the function returns
Without this, imagine how you will have to figure out what each input parameter is for (by wading through the code!)
It is a good practice to document your functions as you develop your code, rather than postponing it to after you have completed your code (“now, what is this parameter meant to do again?” 🤔)
Introducing docstrings!
Programmers conventionally use docstring
s to document functions.
Docstrings are surrounded by triple quotes ("""
) - sounds familiar?
They must be placed in the first line of the body of the function definition, indented.
def square(x):
""" Square the integer x."""
return x ** 2
Generating documentations
If you use docstrings, you can actually generate documentations for your code automatically!
So, it pays to actually document your functions directly in your code itself, rather than trying to do this separately in a separate document.
For example, if you try help(square)
after defining the function above, you will get this:
Help on function square in module __main__:
square(x)
Square the integer x.
You can also use the pydoc module to generate your documentations, perhaps as an HTML. See the link if you are interested, but this is not important for this course.
Style guide
Surprise! There is a separate PEP especially for docstrings! See the official PEP 257 page for more details. The recommendations on the next few pages are based on their guide.