Python-list Digest, Vol 92, Issue 221

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu May 26 06:07:24 EDT 2011


On Thu, 26 May 2011 14:06:56 +1000, Chris Angelico wrote:

> On Thu, May 26, 2011 at 10:58 AM, Richard Parker
> <r.richardparker at comcast.net> wrote:
>> It's time to stop having flame wars about languages and embrace
>> programmers who care enough about possible future readers of their code
>> to thoroughly comment it. Comments are far more valuable than the
>> actual language in which the code is written, IMHO.
> 
> The problem with comments (and documentation in general) is that they
> are often imperfect. 
[snip more stuff I agree with]

It's not the lack of perfection, since no code is perfect, but that 
comments are frequently missing, obsolete, incorrect, or inane: i.e. 
actively harmful rather than just imperfect.

The classic example of what not to write as a comment:

x += 1  # add one to x


One of the regulars here -- Aahz -- often has this quote as his sig:

    "At Resolver we've found it useful to short-circuit any doubt 
     and just refer to comments in code as 'lies'."
     -- Michael Foord paraphrases Christian Muirhead on python-dev,
        2009-03-22


My experience is that comments in Python are of relatively low 
usefulness. (For avoidance of doubt: not *zero* usefulness, merely low.) 
I can name variables, functions and classes with sensible, self-
documenting names. Why write:

x = get_results(arg)  # x is a list of 1 or more results
[... much later]
for y in x:
    # process each result in turn
    do_something_with(y)


when I can write this?

results = get_results(arg)
[...]
for result in results:
    do_something_with(result)


It's better to write self-documenting code, than code + comments.


Another use for comments is to explain *why* rather than *what*. No 
matter how readable your code is, if you don't understand why it is done, 
you can't effectively maintain it. If the why is obvious, you don't need 
a comment.

But for me, the main reason # comments are of relatively little use in 
Python for me is because I write *tons* of docstrings and doctests. Any 
comment which could be useful to know at run-time goes into the 
docstring; what's left over, if anything, becomes a # comment. Between 
self-documenting code and docstrings, I hardly write any # comments.



-- 
Steven



More information about the Python-list mailing list