Docstrings are - unlike regular comments - stored as an attribute of the function they document, meaning that you can access them programmatically.
def func():
"""This is a function that does nothing at all"""
return
The docstring can be accessed using the __doc__ attribute:
print(func.__doc__)
This is a function that does nothing at all
help(func)
Help on function
funcin module__main__:
func()This is a function that does nothing at all
function.__doc__ is just the actual docstring as a string, while the help function provides general information about a function, including the docstring. Here's a more helpful example:
def greet(name, greeting="Hello"):
"""Print a greeting to the user `name`
Optional parameter `greeting` can change what they're greeted with."""
print("{} {}".format(greeting, name))
help(greet)
Help on function
greetin module__main__:
greet(name, greeting='Hello')Print a greeting to the user
name
Optional parametergreetingcan change what they're greeted with.
Just putting no docstring or a regular comment in a function makes it a lot less helpful.
def greet(name, greeting="Hello"):
# Print a greeting to the user `name`
# Optional parameter `greeting` can change what they're greeted with.
print("{} {}".format(greeting, name))
print(greet.__doc__)
None
help(greet)
Help on function greet in module main:
greet(name, greeting='Hello')