How to comment constant values?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Mon Jul 27 01:20:58 CEST 2009


On Sun, 26 Jul 2009 15:42:22 -0700, Bearophile wrote:

> Chris Rebert:
>> Only modules, classes, and functions/methods can have docstrings
>> associated with them.
>> For anything else, you have to use comments; or you can mention them in
>> the docstrings of related things.
> 
> What about adding docstrings to other Python things, especially to
> variables?

Python doesn't have variables, it has objects bound to names. Because 
__doc__ is looked up on the class, not the instance, there's not much 
point in adding a docstring to the instance (even for instances which 
allow attributes to be added). And because names are internally stored as 
strings, you can't add a docstring to the name. So what you ask for is 
impossible.

But of course that could be changed, if there was consensus that what you 
ask for would be useful. But consider the consequences:

# A thought-experiment
>>> margin = 3  # allow a little bit of whitespace
>>> margin.__doc__ = "Extra space in pixels."
>>> help(x)
=> displays "Extra space in pixels."

So far so good. But now consider two equally unacceptable situations:

(1) If the docstring sticks to the object, then you get the docstring 
inappropriately showing up in places where it should:

>>> number_of_widgets = len( [a, b, c] )
>>> help(number_of_widgets)
=> displays "Extra space in pixels."


(2) If the docstring sticks to the name, then you get the docstring 
hanging around when you recycle the name to mean something else:

>>> margin = 15/100.0  # our profit margin is 15%
>>> help(margin)
=> displays "Extra space in pixels."

Now, in a large program, one shouldn't recycle names like that, but in a 
large program, you're unlikely to programmatically look up docstrings. 
Docstrings, and the help() function, are particularly useful in an 
interactive session, which is precisely the time that you're likely to 
recycle names.


In other words, it's currently impossible to bind docstrings to 
"variables" in Python, but even more fundamentally, the request is 
semantically incompatible with the Python name/object binding model.


-- 
Steven



More information about the Python-list mailing list