How to Write Comments in Python

Python makes it easy to comment. A single hash before any piece of code and a comment is born:

# A comment in Python

Maybe not a good comment but a comment it is. It can be on its own line or follow a piece of code:

x = x + 2 # This will be ignored

Multi-line comments are done the same way. One hash per line – unfortunately Python lacks true multi-line comment support. Some people like to use triple quotes instead:

“””
This is bad practice
“””

This, however, is wrong. Although it works it most cases, triple quotes are reserved for documentation strings. Beginners have a tendency to avoid comments. This is a mistake.

Don’t Fear The Comment

When it comes to commenting code, beginners tend to head in two directions. Either they over-comment causing the same problems comment work to solve. Or they go the other direction and don’t comment at all. Both cases are bad.

A lack of comments make your code difficult to maintain. “Eureka” moments become impossible to figure out for future you. Other people reading your code become lost and confused – especially if you’ve used an arcane or obtuse way of solving a problem.

At this point – most programmers will realize the importance of commenting. And so comes the second sin of commenting: too many comments.

Too Much Or Not Enough?

A lack of comments make it difficult to understand your code. Too many make it harder to read. Code that is hard to read is hard to maintain. Worse still – it is ugly. It is an eyesore to look at and the opposite of what code should aspire to be.

Short. Concise. Beautiful.

Too many comments, though, is still better than not enough.