Writing it cleanly

INPUT · Slides

Write a description that can be read back

01 / 07

Python cannot see a comment

You met the # comment in Chapter 1. That was the thing Python ignores completely.

Which means whatever you write in a comment, the program cannot read it back. Look at greet.__doc__ in the code below and all you get is None.

def greet():    # show a greeting    print("good morning")greet()print(greet.__doc__)

Result

good morning
None

02 / 07

The shape of a docstring

Try putting some text wrapped in """ on the line after the def. This is called a docstring, which is to say a string for documentation.

Look at __doc__ the same way as before and this time the text comes straight back. Python has held on to it as the description of this function.

def greet():    """Show a greeting."""    print("good morning")greet()print(greet.__doc__)

Result

good morning
Show a greeting.

03 / 07

help() reads it too

There is a second way in, through the built-in function help(). That one shows you the shape of the function and the description together.

help(greet)

Write that and you get the name of the function, what goes in the brackets, and the docstring, laid out one after another. When you are poking at Python interactively and want to know "what was this again?", this is the standard move.

Exactly how it is laid out shifts a little between versions of Python, so for now just remember that the tool exists.

04 / 07

The one-line docstring

Start with the one-line form. One sentence saying what the function does.

The knack is to write it as a verb. Not "addition" but "return the sum of two numbers". Stop at a noun and you have not said what happens.

For a short function that is all you need.

def add(a, b):    """Return the sum of two numbers."""    return a + bprint(add(2, 3))print(add.__doc__)

Result

5
Return the sum of two numbers.

05 / 07

The multi-line docstring

When the description runs longer, go to several lines. The arrangement is more or less settled:

  • One sentence of summary on the first line
  • One blank line
  • The arguments
  • The return value
  • The closing """ on a line of its own

Pull it out with __doc__ and it is one string, line breaks and all. Python takes the indent off the front of the lines, so it comes out flush to the left.

def divide(a, b):    """Return a divided by b, rounded down.    a: the number being divided    b: the number to divide by    """    return a // bprint(divide(7, 2))print(divide.__doc__)

Result

3
Return a divided by b, rounded down.

a: the number being divided
b: the number to divide by

06 / 07

Classes and methods take them as well

It is not only functions. The same thing goes under the class line of a class and under the def line of a method.

You pull them out with ClassName.__doc__ and ClassName.method_name.__doc__. Each is remembered separately.

class Fruit:    """Represent a single piece of fruit."""    def __init__(self, name, price):        self.name = name        self.price = price    def show(self):        """Print the name and the price."""        print(f"{self.name} is ${self.price}")apple = Fruit("apple", 150)apple.show()print(Fruit.__doc__)print(Fruit.show.__doc__)

Result

apple is $150
Represent a single piece of fruit.
Print the name and the price.

07 / 07

What to write, and what to leave out

What goes in is what somebody using it from outside wants to know.

  • What it does
  • What arguments you hand it
  • What comes back

What stays out is how it works out the answer inside. The code already says that, and writing it twice means fixing it twice every time you change the insides.

Here is how it divides against the # comment. A docstring is the view from outside; a comment is why it was done this way inside. Different place, different reader.