Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

For example, take this Python snippet:python

for index, value in enumerate(value_list): 
    if index < 100:
        print(f"{value} at position {index}")

Many of us will often, almost out of reflex, add comments like:python

# For each element in the value list 
for position, value in enumerate(value_list):
    # Check if the index is within the first 100
    if position < 100:
        # Print the value and it's position
        print(f"{value} at position {position}")


We’ve added absolutely nothing of value here though. Even a glancing understanding of the language makes everyone one of these comments a waste of space.

A more useful comment would explain /why/ we do what we do, for example:

for position, value in enumerate(value_list):
    # Only the first 100 values will be entered into the ballot. Discard the rest.
    if position < 100:
        # Print the values to stdout so entries can be verified by-eye
        print(f"{value} at position {position}")

These comments now provide information not available from the code itself. We’ve actually added something useful.

...

For example, our code snippet above would work just fine1 awfully rewritten as:python

for item in [(i, v) for i, v in enumerate(value_list) if i < 100]: 
    print("{} at position {}".format(item[1], item[0]))


However since it’s so much less readable it would be tempting to just add a bunch of comments explaining what’s going on. By the time you’ve done that though, you may as well just rewrite it in a clearer format.

...