Python 101 - Documenting Your Code

Documenting your code early on is quite a bit more important than most new developers realize. Documentation in software development refers to the idea of giving your variables, functions and other identifiers descriptive names. It also refers to adding good comments. When you are immersed in developing your latest creation, it is easy to create variables and functions with non-descriptive names. A month or a year later, when you inevitably come back to your code, you will spend an inordinate amount of time trying to figure out what your code does.

By making your code self-documenting (i.e. using descriptive names) and adding comments when necessary, you will make your code more readable for yourself and for anyone else who may use your code. This will make updating your code and refactoring your code easier too!

In this chapter you will learn about the following topics:

  • Comments
  • Docstrings
  • PEP8 - The Python Style Guide
  • Other Tools Useful for Documenting Your Code

Let's get started by learning about comments.

What are Comments?

Comments are code that is for you, not for your computer. What I mean by that is that a comment is basically a note to yourself that explains what is happening in that portion of your code. You use comments to explain why you did something or how a piece of code works. When you are starting out as a new developer, it is good to leave yourself lots of comments to refer back to. But once you learn how to properly name your functions and variables, you will find that you don't need comments as much.

However, comments are still recommended, especially for code that is complex and not easy to understand at first glance. Depending on the company you work for, you may also use comments to document bug fixes. For example, if you are fixing a bug, you might include a comment that mentions which bug you are fixing to help explain why you had to change it.

You can create comments by using the # sign followed by some descriptive text.

Here is an example:

# This is a bad comment
x = 10

In the code above, the first line demonstrates how to create a simple comment. When Python goes to execute this code, it will see the # symbol and ignore all the text that follows it. In effect, Python will skip that line and try to execute the second line.

This comment is marked as a "bad comment". While it is good for demonstration purposes, it does not describe the code that follows it at all. That is why it is not a good comment. Good comments describe the code that follows. A good comment may describe the purpose for the Python script, the code line or something else. Comments are your code's documentation. If they don't provide information, then they should be removed.

You can also create in-line comments:

x = 10  # 10 is being assigned to x

Here you once again assign 10 to the variable x, but then you add two spaces and the # symbol, which allows you to add a comment about the code. This is useful when you might need to explain a specific line of code. If you named your variable something descriptive, then you most likely won't need a comment at all.

Commenting Out

You will hear the term "commenting out code" fairly often. This is the practice of adding the # symbol to the beginning of your code. This will effectively disable your code.

For example, you might have this line of code:

number_of_people = 10

If you want to comment it out, you can do the following:

# number_of_people = 10

You comment code out when you are trying out different solutions or when you're debugging your code, but you don't want to delete the code. Python will ignore code that is commented out, allowing you to try something else. Most Python code editors (and text editors) provide a way to highlight multiple lines of code and comment out or uncomment out the entire block of code.

Multiline Comments

Some programming languages, such as C++, provide the ability to create multi-line comments. The Python style guide (PEP8) says that the pound sign is preferred. However, you can use triple quoted strings as a multiline comment.

Here's an example:

>>> '''This is a 
multiline comment'''
>>> """This is also a 
multiline comment"""

When you create triple quoted strings you may be creating a docstring.

Let's find out what docstrings are and how you can use them!

Learning About docstrings

Python has the concept of the PEP, or Python Enhancement Proposal. These PEPs are suggestions or new features for the Python language that get discussed and agreed upon by the Python Steering Council.

PEP 257 describes docstring conventions. You can go read that if you'd like the full story. Suffice to say, a docstring is a string literal that should occur as the first statement in a module, function, class or method definition. You don't need to understand all these terms right now. In fact, you'll learn more about them later on in this book.

A docstring is created by using triple double-quotes.

Here is an example:

"""
This is a docstring
with multiple lines
"""

Docstrings are ignored by Python. They cannot be executed. However, when you use a docstring as the first statement of a module, function, etc, the docstring will become a special attribute that can be accessed via __doc__. You will learn more about attributes and docstrings in the chapter about classes.

Docstrings may be used for one-liners or for multi-line strings.

Here is an example of a one-liner:

"""This is a one-liner"""

A one-liner docstring is simply a docstring with only one line of text.

Here is an example of a docstring used in a function:

def my_function():
    """This is the function's docstring"""
    pass

The code above shows how you can add a docstring to a function. You can learn more about functions in chapter 14. A good docstring describes what the function is supposed to accomplish.

Note: While triple double-quotes are the recommended standard, triple single-quotes, single double-quotes, and single single-quotes all work as well (but single double- and single single-quotes can only contain one line, not multiple lines).

Now let's learn about coding according to Python's style guide.

Python's Style Guide: PEP8

A style guide is a document that describes good programming practices, usually with regard to a single language. Some companies have specific style guides for the company that developers must follow no matter what programming language they are using.

Back in 2001, the Python style guide was created as PEP8. It documents coding conventions for the Python programming language and has been updated several times over the years.

If you plan to use Python a lot, you should really check out the guide. It will help you write better Python code.

Also if you want to contribute to the Python language itself, all your code must conform to the style guidelines or your code will be rejected.

Following a style guide will make your code easier to read and understand. This will help you and anyone else who uses your code in the future.

Remembering all the rules can be hard, though. Fortunately, some intrepid developers have created some utilities that can help!

Tools that can help

There are lots of neat tools that you can use to help you write great code. Here are just a few:

You can run these tools against your code to help you find issues with your code. I have found Pylint and PyFlakes / flake8 to be the most useful. Black is helpful if you are working in a team and you want everyone's code to follow the same format. Black can be added to your toolchain to format your code for you.

The more advanced Python IDEs provide some of the checks that Pylint, etc. provide in real-time. For example, PyCharm will automatically check for a lot of the issues that these tools will find. WingIDE and VS Code provide some static code checking as well. You should check out the various IDEs and see which one works the best for you.

Wrapping Up

Python comes with several different ways to document your code. You can use comments to explain one or more lines of code. These should be used in moderation and where appropriate. You can also use docstrings to document your modules, functions, methods, and classes.

You should also check out Python's style guide that can be found in PEP8. This will help you develop good Python coding practices. There are several other style guides for Python. For example, you might want to look up Google's style guide or possibly NumPy's Python style guide. Sometimes looking at different style guides will help you develop good practices as well.

Finally, you learned about several tools you can use to help you make your code better. If you have the time, I encourage you to check out PyFlakes or Flake8 especially as they can be quite helpful in pointing out common coding issues in your code.

Related Reading

Want to learn more about what you can do with Python? Check out these tutorials:

Copyright © 2022 Mouse Vs Python | Powered by Pythonlibrary