In article <mailman.2126.1306435826.9059.python-l...@python.org>, Richard Parker <r.richardpar...@comcast.net> wrote:
> On May 26, 2011, at 4:28 AM, python-list-requ...@python.org wrote: > > > 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) > > (It occurred to me that I should use a specific subject for this discussion.) > > I'm less inclined to use comments on each line, or selected lines, but rather > use block comments instead. They require more thought and time to write; > however, the intended functionality of the code that follows can be described > in full. Over the years, my use of comments has evolved. I was taught, "You should comment your code". Eventually, I came to realize that the real mandate is, "You should make it easy to understand your code". Comments are just one possible tool to help achieve that goal. Some things that help code be understandable are: * Using good data structures * Using good algorithms * Breaking the code up into manageable pieces (i.e. functions, classes, methods), each of which encapsulates a single concept * Using descriptive names for variables (and functions, classes, methods, etc) All of those fall under the "self-documenting code" umbrella. But, while those things help, I find it's almost always a good idea to document interfaces, i.e. functions. What the arguments are (not just their types, but valid value ranges, and what they mean). What the function returns. What error conditions are possible. And, in general, what the dang thing does. In other words, enough information to use (and test) the function to its fullest extent without ever having to look at the source code. This stuff tends to go in a big block comment at the beginning of the function. Now, what makes Python interesting in this regard is that the big block comment becomes a doc string. You write exactly the same stuff, except now things like help() can get at it, and things like doctest can do even more interesting things with it (I don't actually use doctest, but I do appreciate its coolness). Comments scattered throughout the code tend to be warnings about tricky stuff, references to classic algorithms, references to ticket tracking systems, and the like. Sometimes it's an explanation of what the next bunch of lines of code are doing, although if you've got a lot of those, that's a hint that maybe you need to be refactoring instead. Sometimes I'll drop in suggestions to future maintainers like, "consider refactoring with with perform_frobnitz_action()", or even, "Don't change this without first talking to Fred!" -- http://mail.python.org/mailman/listinfo/python-list