Programming Programmer

Comments in Python - How to Write Great Python Comments?

Comments in Python - How to Write Great Python Comments?

Clarity is king when it comes to writing crisp code that functions just as it was intended. Everyone who wishes to become a proficient Python Developer spends much time mastering Python. But everyone need not write clean, crisp code that is easy to read and understand not only at that moment but even years later. That’s where comments in Python become a crucial factor that will aid your lines of code with high readability which will help you get up to speed in no time while parsing the codes.

Indeed there are ways to increase the readability of your codes like assigning variables an easy name, defining explicit functions, and optimizing your codes by organizing to make them concise. But there are clear instances when Python comments go a long way in helping yourself and even fellow developers understand your code and how it's mapped out.

So without further ado, let’s dive right in by understanding why comments in Python are essential, then understand the different types of Python comments and how to use them, what best practices are, and finally, when not to comment in Python.

What is Comment in Python and why is it so Important?

A comment is a text added to lines of code after a hash symbol (#) to make it more understandable and easy to follow through.

A comment is meant only for developers. They are very core to programming and help in understanding complex functions. Comments are not exclusive only to Python but to all the types of programming languages that exist that developers use to build a program.

Let’s understand how comments in Python are crucial and how they play a key role in your work through two different instances.

Instance 1:

You are working as a Python Developer in a company, and your client “A” needs a last-minute deployment for their web service. Plus you are on a tight deadline. You are left with one option, which is to work as fast as possible, skipping all the commenting and documentation parts which are not crucial at that moment and could be added later.

You put in your 100% effort, deploy the service and deliver results. Client “A” is happy!

As you go back the next day to work on documentation and add comments, you are assigned another priority task or next project which needs your urgent attention. After a few days, you completely forgot about the task.

After some months…..

Client “A” is back with some more requirements. You open your lines of code and started parsing. After a few moments, you start to realize that you are not able to understand the codes, and why exactly you followed a certain way in pulling the results. It’s a complete mess!

Instance 2:

This time you are part of a startup, you are the only one working on a small project. You very well know what your code means, so you might think, what’s the need to add comments or any sort of documentation? It takes time, so it’s easy to skip the part and focus on actual work that is of more value at the moment.

No problem till now. The actual problem starts as your startup grows and your team expands. Now there might be additional developers within your team helping you with the project. You might have been working for a long time and might have written thousands of lines of code, which these newly joined developers are finding difficult to grasp, and are facing trouble understanding properly.

The conclusion from these instances:

Using comments in Python and any other language is helpful not only for you (Future you!) but also for your team members or fellow developers who will continue working on the logic you built.

Types of Comments in Python and how to use them?

Now you have understood the necessity of comments in Python and now we shall further this blog by knowing the types of Python comments and ways to use them:

Basically, there are three types of Python comments:

  1. Single Line comment
  2. Multi-Line comment
  3. Docstrings

We will understand each of them one by one:

1. Single Line comment

This type of Python comment is the most common in Python. They start with a hash mark (#) before your desired comment.

# This is how you write a single-line comment!

[alt_text: Single line comment in Python]

So, what Python does here is it ignores or neglects everything after this hash mark. You can even insert a comment beside a code and still, Python will neglect it and print only the result.

print ("Today it's a full moon") #I am eager to watch!

Today it's a full moon

[alt_text: In-line comment in Python]

According to Python Style Guide, PEP (Python Enhancement Proposals) 8, code must be limited to 79 characters at max per line and 72 characters for inline comments and docstrings. If it exceeds your logic, consider extending it to multiple lines to make it look more appealing. So if that’s the case what is a multiline comment in Python? We will explore that in the next section.

2. Multi-line comment

Multi-line comment in Python is nothing but comments spread out over different lines instead of being only limited to one single line.

Can we use the same single hash mark (#) for multi-line comments?

# This is not

how you comment 

in Python! 

File "<ipython-input-2-79a03133827d>", line 2

    how you comment

        ^

SyntaxError: invalid syntax

[alt_text: Incorrect representation of multi-line Python comment]

The answer is a clear NO! It will return an error!

Python doesn’t have a native multi-line commenting functionality like in Java and other programming languages. For instance:

/* This is how easily 

you can write 

a multi-line comment in Java */

[alt_text: Multi-line comment functionality in Java]

Everything written between /* and */ is overlooked by the Java compiler and doesn’t surface in the output.

Well, worry not! Python does have some tricks up its sleeve!

There are two ways by which Python can accommodate multi-line comments and they are:

  1. Adding a hash mark (#) before every new line.
  2. Using Triple Quotes.

So, what will the first option look like?

Like this.

#This way

#you can write 

#a multi-line comment 

#in Python

[alt_text: Multi-line comment in Python using (#) in every new line]

Writing multi-line comments like this for a few lines of code is easy. But imagine writing comments like this for a complex Python Project. It's cumbersome!

Another way of writing comments is using Triple Quotes:

"""

This is the best way to 

write a multi-line comment

in Python

"""

print("This is a sunny day")


This is a sunny day

[alt_text: Multi-line comments in Python using Triple Quotes]

Before we explain the usage of triple quotes, let me explain how it works.

You can also write a comment in Python using just a string literal by not assigning it to a variable. For example:

'using just a string literal also you can comment'

print ("Today it will be a full moon")

Today it will be a full moon

[alt_text: Unassigned string literal used as Python comment]

Basically, within Python, any string literal which is not assigned to a variable is ignored by the Python interpreter. You can also write multi-line comments using this method like this:

'Using String Literal'

'You can add comment'

'You can also do multi-line comment too'

print ("Today it will be a sunny day")

Today it will be a sunny day

[alt_text: Unassigned string literal used as a multi-line comments in Python]

But the same problem of adding a single quote, again and again, makes it cumbersome! That’s where Triple Quotes come in handy. Just placing those triple quotes at the beginning and at the end will make the entire process of multi-line commenting way easier.

But here you need to be careful. Depending on where you place these multi-line comments, they could become Docstrings, which we will cover in the next section.

3. Docstrings

It is an in-built feature that Python offers for commenting on modules, functions, methods, etc. Docstrings must be written in the first line after defining a function, method, function, etc., using triple quotes.

print ("Today will be a sunny day")

""" This is 

     how you 

      will write 

      a DocString"""

print("Today is Monday.")

Today will be a sunny day

Today is Monday.

[alt_text: Docstrings in Python]

Docstrings are associated with the documentation of a function or method. So adding a multi-line comment using these quotes, one must be very careful to not confuse it with the documentation process.

Python Comments - Best Practices

  • Think always of the long term and comment accordingly. Comments are a way to help you translate what you think now to your future self. Keep that in mind.
  • Add proper concise comments, which help not only you but your fellow developers who will work on it.
  • Read the PEP Style guide for more information.

Python Comments - Worst Practices

  • Avoid W.E.T (Wrote Everything Twice) comments and make it D.R.Y (Don’t Repeat Yourself). This means you shouldn’t write a simple code and explain that through a comment. Which ultimately leads to redundancy.
  • If your code is poor, no amount of commenting will fix it. So avoid smelly comments in Python.
  • Please stay away from posting rude or mocky comments which could hurt the business of the organization you are working with.

Conclusion

Learning how to comment will go a long way in developing and honing your programming skills. By commenting regularly, you will start writing more concise lines of code and in that process will gain a deeper understanding of Python, just like enrolling in a Python Programming Course which will help you learn Python practically through various industry-grade projects.

Feel free to reach out to us through the comment section. Our team will reach out to you soon!