Love to get some feedback on my first python app!!!

Chris Angelico rosuav at gmail.com
Mon Sep 22 10:50:15 EDT 2014


On Tue, Sep 23, 2014 at 12:32 AM, Jean-Michel Pichavant
<jeanmichel at sequans.com> wrote:
> For instance:
>
> cells = ['a', 'b' 'c']
> # print the first cell
> print cell[1]
>
> A bug that is easily spotted thanks to the comment. It's all about implementation versus intentions. Also note that comment should be written for the future self,  and most importantly, for the current others.

I do see your point, but there's a serious problem here of code edits.
It's really easy to zip through and find all occurrences of some name
and change them - and miss the one in the comment. In this particular
case, I'm not actually sure where the bug is: is it in the first line
(should be "cell = ...") or the third ("print cells[1]")? Either way,
the comment doesn't make it any clearer, because the plural rule in
English doesn't always match naming of variables. Also, it's common in
English to count from 1, but in code to count from 0; so there's
another bug (and this might be the one you thought easily spotted) -
it should either be "cell[0]" in the third line, or "print the 1th
cell" in the second.

(Plus, there's a comma omitted. That list has two elements, but I
think it's meant to have three. However, I'm guessing that's a
transcription error, or a construction-in-email error, and nothing to
do with what you're saying.)

Now, compare this similar code:

cells = ['Chris Angelico', 'rosuav at gmail.com', 142857]
# print the email address
print(cells[2])

This says *why* it's doing what it does - what the meaning of the
index is. And it, too, has a clearly visible bug, because when it
prints out an integer, the comment makes it obvious that it's done the
wrong thing. This is, IMO, much more useful. If the code gets edited
(maybe the name used to be in two fields for First Name and Last Name,
and then someone realized how bad an idea that is - but forgot to
update the index), the original intention is visible; if it just says
"print out cell #2", it's not so helpful.

So basically, don't *purely* repeat yourself, but give some info
that's a level behind the code.

ChrisA



More information about the Python-list mailing list