Skip to main content

Any Comments?

Coding meme

Well, if you are trying to read old codes of yours and trying hard to understand, then continue to read as this quick guide might help you to stop your-future-self re-reading this guide.

This guide is based from RealPython Guide on documenting the code.

Few quotes to get you started:

“Code is more often read than written.” ~ Guido van Rossum

Commenting vs Documenting Code

Your code has two customers, your users and your developers.

Commenting is describing your code to developers. So if you don't comment

“If you don’t comment your code, then you will be the only one who can understand it.” ~ Unknown

Documenting is explaning the code and how to use it for customers.

“It doesn’t matter how good your software is, because if the documentation is not good enough, people will not use it.“ ~ Daniele Procida

So why is it important to add comments?

Comments will help the reader to better understand the code, the design and the purpose of it.

“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” ~ Martin Fowler

Here onwards we will look at how to comment your code properly.

Rule #1 of commenting is to tell why. Not what. Not how. A code will be read by a fellow developer or a future you. So it is important to tell why you wrote the code in the first place.

“Code tells you how; Comments tell you why.” ~ Jeff Atwood

Commenting in Python

Comments in Python starts with #.

Basic Comment

def hello_world():
# A simple python application to print hello world
print("Hello World!")

Multi-line Comment

def hello_world():
# Length of a comment should be less than 72 characters.
# A lengthy comment should be broken into multiple lines
print("Hello World!")

Comments are great servants but bad masters. So don't overdo it

Planning and Reviewing

Use comments as a strucuture to your guide writing new pieces of code, but make sure to remove them after.

Describe Code

Use comments to explain why, not what is done or how it is done.

Describe Algorithms

Use comments to explain the thought process behind the Algorithms

A form of tagging

Use comments to tag code that needs to be revisited later. eg:

# TODO: Need to add the logic for edge cases
# BUG: This code is buggy
# FIXME: This code does not work as expected

Comments should

  • Be brief and to the point
  • Be close to the code pieces of what you are describing
  • Not be lengthy and hard to understand
  • Not be redundant
  • Not be have complex formatting, such as tables and lists

Use Python type hints to comment the code by itself.

def add_two_integers(a: int, b: int) -> int:
return a + b

Documenting in Python

Actually a # TODO