Docstrings vs Comments

It appears your teacher is a fan of How to Design Programs 😉

I’d tackle this as writing for two different audiences who won’t always overlap.

First there are the docstrings; these are for people who are going to be using your code without needing or wanting to know how it works. Docstrings can be turned into actual documentation. Consider the official Python documentation – What’s available in each library and how to use it, no implementation details (Unless they directly relate to use)

Secondly there are in-code comments; these are to explain what is going on to people (generally you!) who want to extend the code. These will not normally be turned into documentation as they are really about the code itself rather than usage. Now there are about as many opinions on what makes for good comments (or lack thereof) as there are programmers. My personal rules of thumb for adding comments are to explain:

  • Parts of the code that are necessarily complex. (Optimisation comes to mind)
  • Workarounds for code you don’t have control over, that may otherwise appear illogical
  • I’ll admit to TODOs as well, though I try to keep that to a minimum
  • Where I’ve made a choice of a simpler algorithm where a better performing (but more complex) option can go if performance in that section later becomes critical

Since you’re coding in an academic setting, and it sounds like your lecturer is going for verbose, I’d say just roll with it. Use code comments to explain how you are doing what you say you are doing in the design recipe.

Leave a Comment