Making ensuring your Python code is readily understandable by others is a top priority while developing it. You may achieve this by naming variables clearly, specifying functions explicitly, and arranging your code.
Adding comments is a great and simple method to make your code more readable.
The fundamentals of Python commenting are discussed in this lesson. You will learn how to create comments that are clear and succinct, as well as when it is unnecessary. In addition, you’ll pick up knowledge of:
- Why it’s so important to comment your code
- Best practices for writing comments in Python
- Types of comments you might want to avoid
- How to practice writing cleaner comments
Why Commenting Your Code Is So Important
A program is not complete without comments. Module-level docstrings or inline comments might provide more context for a difficult function.
Before we get into the various comment kinds, let’s examine the value of commenting your code.
Have a look at the two examples below where the programmer neglected to include comments to his
code.
When Reading Your Own Code
Customer A is requesting an urgent rollout of their online service. As time is of the essence, you decide to improvise. Documentation, appropriate commenting, and similar “extra” features will be implemented later.
The due day arrives, and you launch the service promptly. Whew!
You make a mental note to edit the comments later, but your boss interrupts you with a new project that has to be begun right now. After a week, you’ve forgotten all about the code you developed for Client A that needed suitable comments.
Now, fast forward six months, and Client A wants a patch developed for that same service to meet with certain additional criteria. Because you created it, it is your responsibility to keep it in working order. A text editor is opened and….
Just what the heck did you write?!
You’ve spent many hours trying to decipher your previous code, but you’re now more confused than ever. You were in such a haste that you didn’t take the time to correctly name your variables or arrange your functions’ control flow. Worst worse, there are no comments in the script to explain anything!
It’s common for developers to lose track of the intent of their own code, particularly if it was developed a long time ago or under duress. Code may be messier than normal when a deadline is looming and hours of sitting in front of a computer have resulted in bloodshot eyes and tight hands.
Many programmers are just too worn out to go back and comment their code after the project has been turned in. They may spend a great deal of time afterwards attempting to make sense of what they wrote.
Commenting on your work as you go is an excellent method to avoid the aforementioned problem. Respect the Future You
You!
When Others Are Reading Your Code
Let’s say you’re the only programmer on a little Django project. You don’t utilize comments or other documentation since you don’t need it because you have a good grasp of your code. You don’t see the value in taking the effort to compose and update comments.
However, by year’s end, your “little Django project” has ballooned to “20,000 lines of code,” and your manager has asked you to hire more engineers to keep up with it.
The new developers do their best to learn fast, but after only a few days of teamwork, you can see that they’re struggling. You wrote in a very concise syntax and utilized some interesting names for your variables. The new recruits invest significant time in line-by-line exploration of your code in an effort to comprehend its inner workings. It will be a few days before they can assist you with upkeep.
In cases like these, other developers would appreciate the comments you sprinkled throughout your code. Adding comments to your code makes it easier for other developers to rapidly scan and comprehend what you’ve done. Making the conscious decision to annotate your code from the very beginning of a
project.
How to Write Comments in Python
Knowing why it’s crucial to comment your code, let’s go through the fundamentals of doing so.
properly.
Python Commenting Basics
Developers should not leave comments. They provide context for the code to help programmers like yourself comprehend it.
Python comments begin with a hash sign (#) before the first line of code.
comment:
# This is a comment
Anything following the hash mark and before the end of the line is ignored by Python. They are completely portable and may be used inline with other
code:
print("This will run.") # This won't run
The only thing printed out by running the following code is “This will execute.” Nothing else is paid any attention.
Your feedback should be succinct and relevant. Although PEP 8 recommends limiting lines of code to 79 characters or less, it supports capping inline comments and docstrings to 72 characters per. If your remark is going to be longer than that, you may split it up into additional comments.
lines.
Python Multiline Comments
Unlike C, Java, and other programming languages, Python does not support multiline comments.
Go:
# So you can't
just do this
in python
The software will skip through the first line in the preceding example, but it will throw a Syntax Error for the rest.
A remark may be broken out over numerous lines in languages like Java, though.
easily:
/* You can easily
write multiline
comments in Java */
Everything between /* and */ will be disregarded by the system.
Python does not have built-in support for multiline comments, however it is possible to make multiline comments. You may do this in one of two easy methods.
The simplest method is to hit the return key at the end of each line, followed by a hash mark and the next part of your remark.
there:
def multiline_example():
# This is a pretty good example
# of how you can spread comments
# over multiple lines in Python
The computer won’t process any lines that begin with a hash mark.
Multiline strings, where your remark is enclosed in three double quotes, are another option.
quotes:
"""
If I really hate pressing `enter` and
typing all those hash marks, I could
just do this instead
"""
Anything within the triple quotes will be treated as a remark, much as in Java’s multiline comments.
Although this does allow for several lines, it is not a comment. It’s a string that hasn’t been given any special treatment in your code by being set to a variable. Although it won’t be shown in the bytecode, it may still serve as a remark since it will be disregarded at runtime. (You can verify that these strings won’t be included in the bytecode by reading this article.)
Take caution with the placement of these multiline “comments,” since they may become docstrings (documentation strings connected with a particular method or function) if not handled properly. Place one of these bad boys after the definition of a function, and the remark you wrote will be permanently linked to the function.
Use caution, and if in doubt, just place a hash mark after the line. Check out our Documenting Python Code Tutorial to learn more about docstrings and how to attach them to different types of Python code.
.
Python Commenting Shortcuts
The hash marks are a pain to spell out every time you want to make a remark. Is there anything you can do to hasten the process? Here are some tips to keep in mind while you provide feedback.
The usage of numerous cursors is a good place to start. That’s right; using many cursors on the screen at once is exactly what it sounds like it is. To activate the flashing lines, just press and hold the Ctrl (or Command on a Mac) key while left-clicking:
When making similar remarks in different areas, this is the most efficient method.
What if you need to comment out a large chunk of text? Let’s pretend you’re testing for bugs by preventing a specified function from being called. It can take a long time to click each line to remark it out. Toggle comments instead in these instances. To copy a code, select it and hit Ctrl + / (Windows) or Command + / (Mac):
The application will add a hash mark before any highlighted text and completely disregard it.
Your text editor may allow you to collapse comments with a little down arrow on the left if they get too lengthy, whether they are your own or the comments in a script you are reading.
To dismiss the feedback, just click the arrow. This is useful for docstrings that span numerous lines at the beginning of a program or comments that span multiple lines.
When you use all of these techniques together, commenting your code will be a breeze.
painless!
Python Commenting Best Practices
Knowing how to construct Python comments is useful, but it’s as important that those comments be clear and comprehensible.
Here are some guidelines to follow if you want your comments to be taken seriously.
code.
When Writing Code for Yourself
Properly commenting your own code might save you time and frustration. You’ll notice it even if no one else does, and that’s reason enough to fix it. Because you’re a developer yourself, your code must be straightforward.
Using comments as an outline for your code is an excellent method to benefit from them. The comments you add to your code may help you keep track of what has to be done and the overall flow of your program, even if you don’t know how it will come out. To define a function in, for instance, comments might be used.
pseudo-code:
from collections import defaultdict
def get_top_cities(prices):
top_cities = defaultdict(int)
# For each price range
# Get city searches in that price
# Count num times city was searched
# Take top 3 cities & add to dict
return dict(top_cities)
An outline for get top cities() is shown below. You may begin translating your function’s intended behavior into code after you have a firm grasp on its intended purpose.
You can keep track of everything if you sprinkle in remarks like this along the way. As you go through your code, you’ll get insight into what’s still missing from a completely operational script. If you want your code to look good once you’ve “translated” the comments into code, you should get rid of any comments that are no longer necessary.
To aid in the debugging process, comments may be used as well. Remove the old comments to observe how your output changes. Don’t keep the code commented out in your application if you agree with the modification; doing so reduces readability. If you need to restore it, delete it and then access it using version control.
Last but not least, define complex sections of your own code using comments. If you set anything aside and return to it months or years later, you’ll have to put in a lot of work to remember what you did. Do Future You a favor and write down what your code does in case you forget so that you can quickly come back up to speed if you ever need to.
on.
When Writing Code for Others
Even while reading code, people tend to scan and navigate between various sections quickly. Line by line reading of code is only done when something is broken and you need to find out why.
Instead, you’ll probably just skim the variable and function definitions to get an idea of what’s going on. A developer would benefit greatly from having comments that describe what is occurring in simple English.
Use comments to make your code easier to read for other developers. Use inline comments sparingly to explain parts of the code that aren’t self-explanatory. (Although making your code self-sufficient is obviously essential, inline comments may be helpful in this respect.)
A brief note after the def line might be helpful if the name of a method or function is too technical for its intended audience.
light:
def complicated_function(s):
# This function does something complicated
Other developers will be able to quickly grasp what the function performs if you provide a brief description like this.
Regardless of how simple or complex a public function is, it should have an accompanying docstring.
not:
def sparsity_ratio(x: np.array) -> float:
"""Return a float
Percentage of values in array that are zero or NaN
"""
The following text will be permanently connected with your function as its. doc__ property. Your docstring can be better organized with the aid of PEP 257’s recommendations. Most programmers adhere to these guidelines when constructing documentation strings.
Conventions for multiline docstrings are included in the PEP 257 recommendations. These docstrings are included at the very beginning of a file and provide an overview of the whole script and the tasks it is designed to do.
do:
# -*- coding: utf-8 -*-
"""A module-level docstring
Notice the comment above the docstring specifying the encoding.
Docstrings do appear in the bytecode, so you can access this through
the ``__doc__`` attribute. This is also what you'll see if you call
help() on a module or any other Python object.
"""
Any relevant or essential information for the developer reading this docstring will be included in a module-level docstring like this one. It is suggested that all classes, exceptions, and functions be included, along with a brief description of each, in such a document.
each.
Python Commenting Worst Practices
In the same way that there are guidelines on how to write Python comments, there are also certain comment kinds that should never be followed by actual Python code. Several examples are shown below.
few.
Avoid: W.E.T. Comments
The abbreviation “D.R.Y.” refers to the programming adage “Don’t Repeat Yourself,” which suggests that your comments shouldn’t include any unnecessary repetition. A piece of code like this doesn’t need comments since it explains itself.
one:
return a # Returns a
There is no need to add a remark stating that an is returned since it is obvious. You “wrote everything twice,” or “wasted everyone’s time,” if you leave a remark after reading this.
Even if you used comments to organize your code before writing it, you can make the rookie error of using W.E.T. comments. It’s important to delete obsolete comments after you’ve got the code operating well.
unnecessary.
Avoid: Smelly Comments
Code comments may be a “code smell,” or an indicator that there is a larger issue with the code. Comments are one kind of code smell that aims to obscure the real faults in a program. Your code’s comments should provide context and context only. There is no use in adding comments to badly designed code.
First, let’s examine the
example:
# A dictionary of families who live in each city
mydict = {
"Midtown": ["Powell", "Brantley", "Young"],
"Norcross": ["Montgomery"],
"Ackworth": []
}
def a(dict):
# For each city
for p in dict:
# If there are no families in the city
if not mydict[p]:
# Say that there are no families
print("None.")
This is a really chaotic code. Each line of code is prefaced by a remark that describes its purpose. Using more intuitive names for the script’s variables, functions, and collections—like
so:
families_by_city = {
"Midtown": ["Powell", "Brantley", "Young"],
"Norcross": ["Montgomery"],
"Ackworth": [],
}
def no_families(cities):
for city in cities:
if not families_by_city[city]:
print(f"No families in {city}.")
Using straightforward naming conventions allowed us to eliminate all superfluous comments and shorten the code considerably.
It’s not good practice to have comments that are longer than the code they explain. Explaining your work too often is a sign that your code needs to be refactored to make it more readable and understandable.
concise.
Avoid: Rude Comments
While contributing to a development team, you will inevitably encounter this issue. Since several developers are simultaneously modifying the same code, it’s inevitable that your work will be reviewed and modified by others. The occasional person who might be brave enough to post a remark like this
one:
# Put this here to fix Ryan's stupid-a** mistake
In all honesty, you should probably avoid doing this. Even if you know your buddy won’t be upset by it since it’s their code, it’s still inappropriate. How would it look if that statement was left in by mistake and a customer noticed it later? You never know what will be sent to production. Using profanity in your response is not the way to demonstrate your professionalism.
that.
How to Practice Commenting
Just do it! That’s the easiest method to start adding more Pythonic comments to your code.
Get in the habit of leaving comments in your own code. Provide brief notes wherever possible going forward. Make difficult functions easier to understand and always provide a docstring at the beginning of your scripts.
Going back over previous programming is another great approach to hone your skills. Check for places where the code may not make sense and fix them. If it still requires further guidance, a brief note may be added to the code to explain its function.
If people are forking your GitHub repo after seeing your work, this is a great idea. To get them going, explain the steps you took to reach your current state.
Commenting on other people’s code is another way to give back to the community. If you’ve downloaded anything from GitHub but are having problems figuring out what it does, you may make comments as you learn more about the code.
Include your initials and the date in your “signature,” and then send a pull request with the updated code. You may be giving dozens, if not hundreds, of other developers a hand with their next endeavor if your improvements are integrated.