Home » Python » How to Comment Code in Python: Inline, Multiline, and Docstring

About Jeremy Grifski

Jeremy Grifski
Jeremy is the founder of The Renegade Coder, a software curriculum website launched in 2017. In addition, he is a PhD student with an interest in education and data visualization.

How to Comment Code in Python: Inline, Multiline, and Docstring

As we kick off 2020, I wanted to start getting back to some of my favorite content: Python “how to” content. Today, we’ll be looking at how to comment code in Python—a skill we should all have.

To summarize, there are three main ways to make comments in Python. To make inline comments, use the hash mark, #. To make multiline comments, use a hash mark on every line. Alternatively, use triple quotes, """. These kick off a multiline string which can be used to simulate comments. For more details, check out the options below.

Problem Description

One thing I’ve done throughout this series is create content that targets a specific issue and address it with a few solutions. Of course, many of those solutions require some fundamental understanding of how Python works. In other words, at no point have I actually written any of those fundamental articles. Well, I suppose it’s better late than never.

Today, I want to look at a few ways of commenting code in Python. For those that don’t know, comments are ways of documenting code directly. Specifically, a comment is text that has no semantic affect on your programs. In other words, comments don’t do anything but provide context for the reader.

As an example, we might want to write some mathematical expression like the Pythagorean Theorem:

1
2
3
a_squared = 3**2
b_squared = 4**2
c_squared = a_squared + b_squared

Clearly, this expression resembles the Pythagorean Theorem based on variable name choices alone. However, not everyone will be able to tell at first glance. In other words, we might want to add a comment that tells the reader what the purpose of this expression is. For example, we might say “uses the Pythagorean Theorem to compute c^2.” How do we go about doing that? Luckily, this article will give us a few options.

Solutions

In this portion of the article, we’ll take a look at a few different ways to write comments in Python. Keep in mind that this isn’t really an article on commenting styles or even a commentary on how to write comments. Instead, we’ll just be sharing the syntax. It’s up to you to figure out how you want to use the tools provided.

Inline Comments

In Python, you can create a comment using the hash mark, #. As soon as this mark appears, everything following it until the end of the line is considered a comment:

1
2
3
4
# Uses the Pythagorean Theorem to compute c^2
a_squared = 3**2
b_squared = 4**2
c_squared = a_squared + b_squared

Since comments don’t start until the hash mark appears, we can comment the ends of lines as well:

1
2
3
4
# Uses the Pythagorean Theorem to compute c^2
a_squared = 3**2  # Computes a^2
b_squared = 4**2  # Computes b^2
c_squared = a_squared + b_squared  # Computes c^2

Normally, I’m of the belief that your code should be primarily self-documenting. That said, an inline comment here and there can be helpful for future readers—including yourself.

Block Comments Using Inline Comments

Fun fact: Python doesn’t have block comments. In other words, there is no built-in syntax for handling multiline comments. As a result, PEP 8 recommends using repeated inline comments for block comments:

1
2
3
4
5
6
7
# Uses the Pythagorean Theorem to compute c^2.
# First, we compute a^2 and b^2. Then, the
# expression is constructed as a^2 + b^2 and
# assigned to c^2.
a_squared = 3**2  # Computes a^2
b_squared = 4**2  # Computes b^2
c_squared = a_squared + b_squared  # Computes c^2

Again, these comments are probably excessive; their role is to provide an example of a block comment.

Block Comments Using Multiline Strings

With all that said, it’s possible to simulate block comments with multiline strings:

1
2
3
4
5
6
7
8
9
"""
Uses the Pythagorean Theorem to compute c^2.
First, we compute a^2 and b^2. Then, the
expression is constructed as a^2 + b^2 and
assigned to c^2.
"""
a_squared = 3**2  # Computes a^2
b_squared = 4**2  # Computes b^2
c_squared = a_squared + b_squared  # Computes c^2

Now, that looks a little cleaner to me. In addition, it’s a bit easier to manage in source code in my opinion.

That said, keep in mind that this isn’t a true comment. We’ve instead created a string constant which isn’t assigned to a variable. In practice, this isn’t really an issue as the strings will get optimized out in the bytecode.

Another word of caution: sometimes this style of comment can be interpreted as a docstring. For example, if we insert this comment just below a function header, we’ll have created a docstring for documentation purposes:

1
2
3
4
5
6
7
8
def pythagorean_theorem(a, b):
  """
  Computes the length of the squared third leg of a right triangle.
  """
  a_squared = a**2
  b_squared = b**2
  c_squared = a_squared + b_squared
  return c_squared

In this example, our multiline comment is actually a docstring which we can use to document the method:

01
02
03
04
05
06
07
08
09
10
11
def pythagorean_theorem(a, b):
  """
  Computes the length of the squared third leg of a right triangle.
  :param a: the length of the first leg of the triangle
  :param b: the length of the second leg of the triangle
  :return: a^2 + b^2
  """
  a_squared = a**2
  b_squared = b**2
  c_squared = a_squared + b_squared
  return c_squared

Then, this docstring becomes a runtime attribute of the function. In other words, we can inspect that attribute as follows:

1
print(pythagorean_theorem.__doc__)

As you can see, docstrings aren’t like comments in the sense that docstrings still exist at runtime—regular comments do not. Many IDEs and other tools can then extract these docstrings for documentation purposes. How cool is that?

Challenge

At this point, I’d usually measure performance, but I didn’t feel like that would be applicable. Instead, let’s jump straight to the challenge!

Now that we know three different ways to comment code in Python, let’s talk about good commenting practices. In the comments below, share at least one tip you recommend when it comes to commenting code. Feel free to share anything from commenting styles to commenting etiquette. Bonus points for anything that’s Python specific.

As always, I’ll share my own tip below as well! If possible, I’d love to get a little discussion going. Depending on how it goes, I might compile the results in another article.

A Little Recap

And with that, we’re all done. As always, here’s a little recap of our three ways to comment Python code:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
# Here is an inline comment in Python
 
# Here
# is
# a
# multiline
# comment
# in
# Python
 
"""
Here is another multiline comment in Python.
This is sometimes interpretted as a docstring,
so be careful where you put these.
"""

Published on Web Code Geeks with permission by Jeremy Grifski, partner at our WCG program. See the original article here: How to Comment Code in Python: Inline, Multiline, and Docstring

Opinions expressed by Web Code Geeks contributors are their own.

(0 rating, 0 votes)
You need to be a registered member to rate this.
Start the discussion Views Tweet it!
Do you want to know how to develop your skillset to become a Web Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. Building web apps with Node.js
2. HTML5 Programming Cookbook
3. CSS Programming Cookbook
4. AngularJS Programming Cookbook
5. jQuery Programming Cookbook
6. Bootstrap Programming Cookbook
and many more ....
I agree to the Terms and Privacy Policy

Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of