Docstring vs. Comment

I hope y’all don’t get annoyed with me. I’m wondering what’s the difference between a doctoring and a comment at the beginning of a program. For example:

''' This program prints a user's age '''

vs

# This program prints a user's age 

The difference is in visibility. The following example uses functions to show the difference, but the same applies to modules:

>>> def func_with___doc__():
...     "This function has a docstring."
...     pass
... 
>>> func_with___doc__.__doc__
'This function has a docstring.'
>>> help(func_with___doc__)
Help on function func_with___doc__ in module __main__:

func_with___doc__()
    This function has a docstring.

>>> def func_with_comment():
...     # This function has a comment
...     pass
... 
>>> func_with_comment.__doc__
>>> help(func_with_comment)
Help on function func_with_comment in module __main__:

func_with_comment()

Docstrings are far more helpful to users of your code :slight_smile:

1 Like

Thanks Zachary. Can you suggest an instance when I’d want to use a comment over a docstring?

Use comments for prose that’s useful to someone reading the source, but not to someone using the code in their own separate project or otherwise using the help function on your object. For example, module-level docstrings usually have a short description of what the module holds, and may also have a leading comment containing the license for the code in the module.

(Note that that’s not to say that the license is not useful to someone using the code, but users are likely to have found the license elsewhere :slight_smile: )

1 Like

[…]

See also these documents for excellent recommendations on making the
most of docstrings:

https://www.python.org/dev/peps/pep-0257/
https://www.python.org/dev/peps/pep-0287/
2 Likes