bell notificationshomepageloginNewPostedit profile

Topic : Re: When documenting Python, when should I use docstrings and when should I use comments? Python programming language provides two mechanisms for documenting a function, a module or a class: Comments - selfpublishingguru.com

10% popularity

PEP 8 -- Style Guide for Python Code categories comments and document strings (a.k.a. docstrings) under comments sections.

Comments

Block Comments
Inline Comments
Documentation Strings

Block comments generally apply to some (or all) code that follows them and are indented to the same level as that code.

Inline comments are unnecessary and in fact distracting if they state the obvious.

A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition.

Now to answer your question

Docstrings 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).

In-code comments are to explain what is going on to people those who want to extend the code. These will not normally be turned into the 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 (credits) rules of thumb for adding comments are to explain:

Parts of the code that are necessarily complex. (Optimisation comes to mind).
Workarounds for the 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.


Load Full (0)

Login to follow topic

More posts by @Bryan361

0 Comments

Sorted by latest first Latest Oldest Best

Back to top