A docstring is a string literal that documents a module, function, method, or class. In Python, it is usually written with triple quotes and placed immediately after the definition or at the beginning of a module. section 3.5 section 4.12
Use docstrings to expose a construct’s external purpose and behavior:
- Describe what a function does and which parameters it takes. section 9.1
- Separate public documentation from comments, which explain specific internal implementation details. section 3.5 section 9.1
- Write a concise synopsis first, leave a blank line, and then add multiline details when needed. section 9.1
- Access a function’s documentation through its __doc__ property; browsing tools and help() can use the same value. section 9.1 section 9.9.2
Function documentation
def fact(n): '''Return the factorial of the given number.''' r = 1 while n > 0: r = r * n n = n - 1 return r print(fact.__doc__) # Return the factorial of the given number. section 9.1
Listing 3.1 File wo.py
"""wo module. Contains function: words_occur()""" #1
# interface functions #2
def words_occur():
"""words_occur() - count the occurrences of words in a file."""
# Prompt user for the name of the file to use.
file_name = input("Enter the name of the file: ")
# Open the file, read it and store its words in a list.
file = open(file_name, 'r')
word_list = file.read().split() #3
file.close()
# Count the number of occurrences of each word in the file.
occurs_dict = {}
for word in word_list:
# increment the occurrences count for this word
occurs_dict[word] = occurs_dict.get(word, 0) + 1
# Print out the results.
print(f"File {file_name} has {len(word_list)} words
{CA]({len(occurs_dict)} are unique)")
print(occurs_dict)
if __name__ == '__main__': #4
words_occur()
Inspect a small module containing both a module docstring and a function docstring, alongside comments that describe implementation steps. section 3.5





