Writing Comments in Python

Introduction

It’s critical to ensure that your Python code is easily understandable by others when writing it. Clearly naming variables, providing explicit functions, and structuring your code are all excellent approaches to accomplish this.

Using comments is another great and simple technique to improve the readability of your code.

This course will go over the fundamentals of writing comments in Python. You’ll learn how to create clear and succinct remarks, as well as when you might not need to write any at all.

You’ll also discover:

  • Why is it critical to comment your code?
  • Best practices for creating Python comments Types of comments you should avoid
  • How can I get better at writing cleaner comments?

Why is it vital to comment your code?

Code commenting is a very useful skill to develop early when learning to code. Commenting can take the shape of module-level docstrings or inline explanations that help clarify a complicated function.

Before we get into the various types of comments, let’s take a closer look at why it’s so crucial to comment your code. Consider the following two circumstances in which a programmer has chosen to leave their code uncommented.

When it comes to reading your own code

Consider the case when you are able to fulfill a client’s deadline and deploy your application without all the extras such as —documentation and correct commenting, with the intention of doing so later.

Another project takes off before you can comment your code, and you entirely forget about it after a few days.

After a few months, the client returns and requests a patch. After you’ve opened your code, you try to figure out why you did things the way you did.

You spend hours analyzing your old code, but you’re entirely lost in it. You were in such a hurry that you didn’t correctly name your variables or set up your functions in the proper control flow. Worst of all, there are no script comments to tell you what’s going on!

Developers frequently forget what their own code accomplishes, particularly if it was written a long time ago or under duress.

Leaving comments as you go is an excellent approach to avoid the problem described above. Be kind to yourself in the future!

When Someone Else Is Reading Your Code

Consider the following scenario: you are the sole developer on a small project. You know your own code well enough that you don’t need comments or other forms of documentation, and you prefer it that way. You don’t see the value in leaving comments because they take time to write and you don’t see the point.

As you work on your project, you notice that your code has grown from 100 to 20,000 lines, and your boss is bringing in another developer to help you maintain it.

You spent days attempting to get him up to speed on the project because you didn’t comment your code, and then you noticed now that you have a big problem. He doesn’t comprehend your variable names, and you’re wasting time explaining it to him.

In circumstances like this, using comments throughout your code can benefit other engineers. Other developers can rapidly browse over your code and grasp how it all works thanks to comments. If you choose to remark your code from the beginning of a project, you can help ensure a smooth transition.

Python Comments: How to Write Them

Let’s go over the basics so you know how to properly comment your code now that you know why it’s so important.

Simply use the hash mark # before your desired comment to compose a comment in Python:

# This is a python comment

Everything after the hash mark and up to the end of the line is ignored by Python. You can put them wherever you want in your code, including inline with other code:

print("Hello World")  # This won't run

You will only see the output  “Hello World” when you run the above code. Everything else is  ignored.

Short, sweet, and to-the-point comments are preferred. While PEP 8 recommends reducing code lines to 79 characters or less, it only allows 72 characters for inline comments and docstrings. If your comment is close to or exceeds that length, you should break it up into many lines.

Multiline Comments

Python’s multiline comment is different from languages like Java and C

# I am writing a multiline
comment in Python. This will not work
well. Syntax error will occur

Python will overlook the first line in the preceding example, but the remaining lines will result in a Syntax Error.

A language like Java, on the other hand, makes it simple to spread a comment across numerous lines:

/* I am writing a multiline
comment in Java. This will work in
Java*/

The software ignores everything between /* and */.

While Python does not have native multiline commenting support, it is possible to write multiline comments. There are two easy ways to accomplish this.

The first method is to simply press the return key after each line, add a new hash mark, and continue from there:


    # This is a pretty good example
    # of how you can spread comments
    # over multiple lines in Python

You can also use multiline strings by enclosing your comment in a set of triple quotes as follows:

"""
This is a pretty good example
of how you can spread comments
over multiple lines in Python
"""

Best Practice for writing python comments

While knowing how to write comments in Python is useful, it’s also critical to ensure that your comments are clear and understandable.

Check out these pointers to help you write comments that truly support your code.

When Writing Code for Yourself:

  • use comments as outline for your code
  • use comments as a way to keep track of what’s left to do
  • use comments as part of the debugging process. Comment out the old code and see how that affects your output
  • use comments to define tricky parts of your own code

When Writing Code for Others

Reading code is no different. People want to skim and hop back and forth across text. You’ll probably only read code line by line if something isn’t working and you need to figure out what’s wrong.

  • use comments to explain what’s happening in plain English to assist other developer
  • use Inline comments sparingly to clear up bits of code that aren’t obvious on their own.
  • use comments to explain complicated method or function whose name isn’t easily understandable
  • include docstring for any public function whether its complicated or not

Worst Practices in Python Commenting

Don’t Repeat Yourself

Your comments should be D.R.Y. Don’t repeat yourself, you don’t need to comment a piece of code that sufficiently explains itself, like this one:

return a  # Returns a

Avoid Smelly Code

Commenting should support your code, not try to explain it away. If your code is poorly written, no amount of commenting is going to fix it.

Avoid Rude Comment

Pay attention to your comments when working in a group. Your remark should support the code rather than criticize or disparage others. Avoid rude comments as seen in the example below;

# Put this here to fix Kofi's stupid code** mistake

How to Practice Commenting

Begin writing comments in your own code for yourself. From now on, make it a point to include brief comments whenever possible. Put a docstring at the top of all your scripts and add some clarity to complex functions.

Going over old code that you’ve created is another fantastic approach to practice. Look for any areas of the code that don’t make sense and clean it up. Add a small note to help describe the code’s purpose if it still needs some further help.

Conclusion

Learning to comment your code effectively is a useful skill. You’ll not only learn to write more simply and concisely in general, but you’ll also develop a better comprehension of Python.

Knowing how to write comments in Python will make all developers’ lives easier, including yours! They can both help other developers understand what your code does and help you re-acquaint yourself with previous code.