Code comments that I find helpful

I’m a huge believer in code quality. When I write code, I put in a lot of effort to make it be as easy to read and understand as possible. Because code is read much more often than it’s written, by writing your code in a way that’s easy to understand you’re saving lots of time for the developers who are going to read your code in the future (one of them being future you) and you’re making it easy for them to build on your code and extend it.

As we all know, a big part of writing good code is comments that explain crucial points about the code. This is what this blog post is about.

Making good code comments is not a trivial thing. We’ve all seen comments like this:

x += 1 # Increment x by 1

Comments like that are not only unhelpful but they are outright harmful, because they add noise to the code; they grab our attention but then don’t give us any useful information. Attention is a scarce resource that shouldn’t be wasted.

Because adding comments to code adds noise, we need to make sure that our comments deliver the maximum amount of useful information in the minimum amount of noise. In this blog post I’ve listed a few kinds of comments that I put in my code to make it as clear as possible with as little noise as possible.

Comment braces

Here is a style of comments I picked up a few years ago by reading someone else’s code, and which proved really helpful since then:

def calculate_length_of_recurrent_perm_space(k, fbb): # ... ### Doing phase one, getting all sub-FBBs: ################################ # # levels = [] current_fbbs = {fbb} while len(levels) < k and current_fbbs: k_ = k - len(levels) levels.append( {fbb_: fbb_.get_sub_fbbs_for_one_key_removed() for fbb_ in current_fbbs if (k_, fbb_) not in cache} ) current_fbbs = set(itertools.chain(*levels[-1].values())) # # ### Finished doing phase one, getting all sub-FBBs. ####################### ### Doing phase two, solving FBBs from trivial to complex: ################ # # for k_, level in enumerate(reversed(levels), (k - len(levels) + 1)): if k_ == 1: for fbb_, sub_fbb_bag in level.items(): cache[(k_, fbb_)] = fbb_.n_elements else: for fbb_, sub_fbb_bag in level.items(): cache[(k_, fbb_)] = sum( (cache[(k_ - 1, sub_fbb)] * factor for sub_fbb, factor in sub_fbb_bag.items()) ) # # ### Finished doing phase two, solving FBBs from trivial to complex. #######

I call these “comment braces” because they look like huge vertical braces that have code in them. Even though these comments are quite bulky, I still really love them because they divide the code into different segments, which is very helpful when you have a piece of code that can be logically separated into different segments. (Of course, if you can refactor these different segments into different functions, that would be ideal, but in many cases it’s not practical.)

This style of commenting makes it easier to read the code casually, because when you’re reading a line in the code you only need to think how it relates to the lines in its section, and not how it relates to the lines in the different sections.

Until challenged

“Until challenged” is a short two-word comment that communicates a common programming idiom:

def __lt__(self, other): found_strict_difference = False # Until challenged. all_elements = set(other) | set(self) for element in all_elements: if self[element] > other[element]: return False elif self[element] < other[element]: found_strict_difference = True return found_strict_difference

We’ve all written algorithms where we set a variable to a boolean, and then later we might flip it and we might not depending on some condition, and eventually we’re going to check the value of that variable and possibly return it. Writing a comment “Until challenged” after a variable assignment communicates that we’re using this idiom.

It might be unclear to people who aren’t familiar with it, so it’s a compromise between brevity and understandability. If you want to make it more universally understandable, you can add a few words like “Set to False until we possibly discover a difference and set it to True”.

Establishing current state

Also known as, “the manual assert.” Sometimes it’s useful to make a comment somewhere in the middle of the function that describes what we’ve accomplished by this point, what is the current state, and what we’re going to do now. Example:

# ... if self.is_degreed and (perm.degree not in self.degrees): raise ValueError # At this point we know the permutation contains the correct items, and # has the correct degree. Now, to calculate its index number. if perm.is_dapplied: return self.undapplied.index(perm.undapplied) # ...

I love this kind of comment. What all good comments have in common is that they’re saying what your internal monologue would say if you tried to read the code and understand it without comments, and this comment is no different.

Clarifying else keyword

One thing that can be confusing when reading Python code is when looking at the else part of a long if-else clause, and not being sure what condition it is. This is where I like to add a comment reiterating the condition:

if actual_item_test is None: if isinstance(single_or_sequence, collections.Sequence): return tuple(single_or_sequence) elif single_or_sequence is None: return tuple() else: return (single_or_sequence,) else: # actual_item_test is not None if actual_item_test(single_or_sequence): return (single_or_sequence,) elif single_or_sequence is None: return () else: return tuple(single_or_sequence)

Note the comment after the middle else . It tells you which condition should be true for this else clause to be executed, so you don’t have to trace it back to the original if line.

That’s all I’ve got for now. I’ll be happy to hear your code commenting tips!

Ram Rachum I’m a software developer based in Israel, specializing in the Python programming language. I write about technology, programming, startups, Python, and any other thoughts that come to my mind. I’m sometimes available for freelance work in Python and Django. My expertise is in developing a product from scratch.

Newer post · Older post