Docstrings versus comments in my code

March 30, 2008

One of the great not quite arguments in the Python world is between docstrings and comments, specifically which one you should use in your code. My answer is that I use both, although more comments than docstrings, but I use them for different things.

My comments are primarily written as internal documentation; how a function operates, why it operates that way, the high level logic and structure of the code, and so on. Docstrings, when I write them, are external documentation, covering things like how to use a module, a class, or a function.

Since I mostly write Python code for myself, my comments shade into a bit of external documentation; often I stick a little summary of the function into a comment instead of a docstring. Partly this is because I feel that comments are less formal than docstrings; as docstrings actually are external documentation, I feel the need to make them decent external documentation.

(And sometimes I hijack docstrings for entirely unrelated purposes, since they can be easily looked at from inside Python. DWiki's code uses docstrings to describe how to use text macros, for example, because it means that I can just embed usage descriptions into the actual macro functions instead of having to maintain separate help text somewhere else.)

What I see as the formality of docstrings also makes me nervous about writing them in the 'wrong' format, or at least a less than helpful and clear format. These days there does seem to be a relatively consistent docstring format for things, but I don't think it's very well described anywhere I could easily find (PEP 257 does not qualify).

(This entry is sort of inspired by reading this.)

Comments on this page:

From at 2008-04-06 02:53:56:

I was somewhat amused by PLY's hijacking of docstrings (an example).

I've also found that the epytext docformat has a good usefulness to formality ratio; however, my previous experience was with JavaDoc, so I'm biased.

- Chris Leary

By cks at 2008-04-12 23:46:08:

I should have been clearer about what I meant by 'format'. I'm not so concerned about how to mark up the text for rich-text rendering; I'm more concerned about how to clearly communicate things like expected function arguments and what it returns and so on.

(And I think it gets worse for classes.)

Written on 30 March 2008.
« Tradeoffs in where you store volume management metadata
The quote of the time interval, on XML »

Page tools: View Source, View Normal, Add Comment.
Login: Password:
Atom Syndication: Recent Comments.

Last modified: Sun Mar 30 23:38:05 2008
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.