I think docstrings in Python are for everything, not just public things

January 25, 2017

In my entry on my mixed feelings about docstrings, I mentioned that my most recent Python code was all comments and no docstrings, but also that it was a program instead of a module. So here's a question: should that matter for whether or not you use docstrings? The obvious related question is whether docstrings are for documenting everything in a module, or only the things people are supposed to use.

My best current answer is that if you're going to use docstrings at all, I think that they should be for everything. It's not that docstrings are how you make public documentation, things that you intend that people will use help() on and so on; instead, it's that docstrings are simply the Pythonic way to write function, method, class, and module documentation, whether those are intended for public use or not. Signaling which things are public versus private is best done through other mechanisms (such as a module level __all__ with public exports).

(At this point I will pause to admit that I took a quick look through the standard library and it doesn't seem to be entirely consistent on this. Most things that appear to be internal functions and that have documentation at all seem to use docstrings, but some of them have one or two line comments at the start where docstrings would normally go.)

Of course there are some things that you can't document with docstrings; constants and variables can't have docstrings attached, so you need to either use comments or cover them in the module level documentation.

(Here I'm talking about 'what this function does and how you call it' sort of documentation. Other sorts of commentary about the code and how things operate still go in comments because there isn't any other place where they belong, so you'll find those sort of comments scattered through the standard library as necessary.)

I also have no idea if this is a widespread view in the Python community. I have the impression that it is and the Django source code seems to use docstrings to document functions and so on, but it could be that people now see comments as the way to go outside of public stuff that should show up in help().

(I'll probably try to shift how I document things to docstrings for the next piece of Python code I write, assuming I remember this by then and don't give up in annoyance.)

Written on 25 January 2017.
« Linux desktops and pre-packaged machines from big vendors
Things that make Go channels expensive to implement »

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

Last modified: Wed Jan 25 01:32:47 2017
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.