Table of contents
Text Link
Text Link

Commenting the Right Way in Python Code

print('Hello world')

If you're familiar with programming languages and the Python syntax and come across a line like this, you immediately know its purpose.

def func():
   print('Hello world')
func()

If you're already familiar with the concept of functions, you will say that this chunk of code does the same job; it outputs Hello world to your standard output.

No matter how complex your code execution is, if you've been working on it for a long time, you will likely know what you're doing, even if you haven't looked at it for a while. This is a perfect world. Nothing distracts you from your code, you do exactly what you want and how you want.

There is another world beyond your bubble— the one that is not confined to your style and preferences. This world includes other programmers and engineers with different experience, who may not always agree with you or fully comprehend your code readability, including indentations, context, and even scripts.

Imagine a situation where a developer is interested in your project and wants to contribute with an additional feature. How can that person begin? What if you're turning your idea into a start-up and want to hire some people? Or, even a more radical idea, what if you're going to work at a company and build a career there? Will you tell everyone in person about your code in the most explicit details? Of course not; you need to communicate your ideas and decisions so that everyone can understand them, even people who will look at your code when you're fired and long gone from the company. So what's the best way to do it? The answer is simple — technical documentation and detailed descriptions.

Purpose

Unfortunately, only a few people want to write standalone technical documentation. Don't be upset; after years of development, software engineers found a handy shortcut. You can write documentation inside your block of code as comments at specific places. Doing it in this way, you can achieve three crucial benefits at the same time.

  1. By writing comments, you give yourself and your peers a clue about the purpose of your classes, functions, or even specific sections of code.
  2. Some IDEs can parse these comments and give you quick info about the function/class/module you will use.
  3. Special software allows you to generate documentation in HTML or PDF form and send it to anyone you need.

But remember that we are not talking about comments in general. We are talking about Python comments. They are special in the same way that anything is special in Python. So, let's finally learn about them!

 

Single-line comments

The single-line comments are the most straightforward part of “code” you can write in Python.

To do so, you just use “#” and write your comment right after it.

# Writes “hello world” to the standard output
print('Hello world')

This is also called a block comment (because it's on the same level as the code you're commenting on).

 You can also write inline comments. Please remember a simple PEP-8 recommendation: Separate the piece of code and the # symbol with at least two spaces.

print('Hello world')  # Writes “hello world” to the standard output

Now, even your grandmother (if she didn't know anything about programming) knows what this line is doing. Although, you might want to explain the “standard output” to her. 

 The crucial aspect of the #-comments is that an interpreter completely ignores them. So, if nothing stops you, you can comment your lines of code this way.

print(
   1,  # The number one
   2,  # The number two
   3,  # The number three
   float('nan')  # Not a number
)

Note: even if I showed you this silly example, please keep your comments meaningful and valuable.

Multi-line comments

Python doesn't have a special syntax for multiline comments. You just need to use # for each line to leave this type of comment.

Remember that if you have multiple paragraphs, you should separate them by a new line with a single #.

# Is this a multiple-line comment?
#
# To write long comments
# Use three quotes at each end
# They are called docstrings
Share this article
Get more articles
like this
Thank you! Your submission has been received!
Oops! Something went wrong.

Level up Python skills and advance your career

• Wide range of learning tracks for beginners and experienced developers

• Study at your own pace with your personal study plan

• Focus on practice and real-world experience

Learn Python Free
No credit card required

Strings and docstrings

Python wouldn't be Python if comments weren't special. As promised, Python has a particular way to write comments: docstrings (as in documentation strings)

Docstrings are not regular comments that start with the #. An interpreter does not ignore them. It's a string literal that occurs as the first statement in a module, function, class, or method definition.

You can retrieve the docstring using the “help” function or a special dunder method: __doc__. The idea and possibility of this way of documenting your code are so big, that it even has its own PEP.

If you have already read my previous article about strings (if you haven't, read it after this one), then you know that you can use triple quotes or triple-double quotes (however, it's recommended to use triple-double quotes). That is, '''Single-triple.''' or “"”Double-triple.”"”.

Docstring guidelines imply that the text within them holds importance not only for you, but also for any other reader. It describes your objects, functions, and modules. Place information there carefully since it might be used with document generator software.

Here are some examples:

class Utopianium:
   """
   All world problems will disappear as soon as I complete this class. 💖
   """




help(Utopianium)

The output:

utopianium code output

Here is another example:

def my_sum_function(*args, **kwargs) -> str:
   """ This is a unique sum function that I made myself
   :param args: numbers
   :param kwargs: some magic
   :return: result string message
   """
   return f'The result is: {sum(*args, **kwargs)}'

If you hover over this example in PyCharm, you can see excellent formatted info that was generated:

info generated

You can look at the built-in library docs as well. For example, the math library:

math library

Note: It’s worth mentioning that you can use a single-line docstring with triple quotes.

def foo():
   """Do nothing"""
   pass

Wrap-up

Commenting is a simple yet valuable technique you should acquire to communicate your code to others.

There are three ways to write comments:

  1. Block comment method. They start with a # and are followed by a text. A simple way to leave a reminder, make a note for a variable, or add some details on the purpose. The interpreter removes them from the code (you can’t use the “help” function to see them).
  2. Inline comments are the same as single-line comments. Moreover, they can start at any point in your code if they do not cause a syntax error. Use them when you have to write a large amount of text and docstrings are not suitable for this purpose.
  3. Docstrings are the ultimate way of writing documentation. Do not abuse them, and use them with caution. There are no unified rules on what to add to docstrings, but if you’re interested, you might want to look at the style guide used in numpy or the reStructuredText guide.

 Your comments add value to your code and make your program more understandable for others and for yourself (without extra detailed explanations). Good luck with using comments and docstrings in your code. 

Related Hyperskill topics

Get more articles like this
Thank you! Your submission has been received!
Oops! Something went wrong.

More on this