Tip 7 Self-Document Your Code

Pythonic Programming — by Dmitry Zinoviev (15 / 116)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Wrap Long Lines | TOC | Do Not Misuse Docstrings 👉

★2.7, 3.4+ A module, function, method, and class can and should be self-documented. Self-documentation is a feature that allows you to combine object implementation and object description in one piece of code. As a courtesy to yourself and your future customers, always self-document everything that can be self-documented!

The description part of self-documentation is called a docstring. A docstring is implemented as a string literal (an unassigned string) as the first statement of the object’s body.

Despite a common belief, a docstring does not have to be a multiline (triple-quoted, see Tip 4, Use Quotes of All Sorts) string. You can use single-quoted and double-quoted strings as docstrings, except that, naturally, they are limited to a single line. Also, despite a common belief, the docstring must be the first statement of an object. If an unassigned string is not the first statement, Python does not recognize it as a docstring.

A docstring explains the purpose of the object that it documents. For functions and methods, it also explains the meaning of the parameters and the return values. Here is an example of a docstring of a popular built-in function len:

​ ​def​ ​len​(obj):
​ ​'Return the number of items in a container.'​
​ ​# Do something​

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.