Documentation: Code Comments

Learn what it means to document code in Python, especially through code comments.

We'll cover the following

This lesson is about documenting code in Python from within the code. Good code is self-explanatory but is also well-documented. It is a good idea to explain what it is supposed to do (not how).

One important distinction that should be made is that documenting code is not the same as adding comments to it. Let's briefly touch on the subject of code comments, just to establish some points that will make a clearer distinction between the two.

Code documentation is important in Python because, since it's dynamically typed, it can be easy to get lost in the values of variables or objects across functions and methods. For this reason, stating this information will make it easier for future readers of the code.

There is another reason that specifically relates to annotations. They can also help in running some automatic checks, such as type hinting, through tools such as mypy or pytype. We will find that, in the end, adding annotations pays off.

Code comments

As a general rule, we should aim to have as few code comments as possible. That is because our code should be self-documenting. This means that if we make an effort to use the right abstractions (like dividing the responsibilities in the code throughout meaningful functions or objects), and we name things clearly, then comments shouldn't be needed.

Note: Before writing a comment, try to see if you can express the same meaning using only code (that is, by adding a new function, or using better variable names).

In our opinion, and in opinions stated in other literature on software engineering, comments in code are a symptom of an inability to express code correctly.

However, in some cases, it's impossible to avoid adding a comment in code, and not doing so would be dangerous. This is typically the case when something in the code must be done for a particular technical nuance that's not trivial at first glance (for example, if there's a bug in an underlying external function and we need to pass a special parameter to circumvent the issue). In that case, our mission is to be as concise as possible and explain in the best possible way what the problem is and why we're taking this specific path in the code, so the reader can understand the situation.

Get hands-on with 1200+ tech skills courses.