10. COMME N T S, DOCS T R INGS, AND T YPE HINTS

The comments and documentation in your source code can be just as important as the code. The reason is that software is never finished; you’ll always need to make changes, whether you’re adding new features or fixing bugs. But you can’t change code unless you understand it, so it’s important that you keep it in a readable state. As com- puter scientists Harold Abelson, Gerald Jay Sussman, and Julie Sussman once wrote, “Programs must be written for people to read, and only incidentally for machines to execute.”

Comments, docstrings, and type hints help you maintain your code’s legibil- ity. Comments are short, plain-English explanations that you write directly in the source code and the computer ignores them. Comments offer help- ful notes, warnings, and reminders to others who didn’t write the code, orsometimes even to the code’s programmer in the future. Almost every pro- grammer has asked themselves, “Who wrote this unreadable mess?” only to find the answer is, “I did.”

Docstrings are a Python-specific form of documentation for your func- tions, methods, and modules. When you specify comments in the docstring format, automated tools, such as documentation generators or Python’s built-in help() module, make it easy for developers to find information about your code.

Type hints are directives you can add to your Python source code to specify the data types of variables, parameters, and return values. This allows static code analysis tools to verify that your code won’t generate any exceptions due to incorrectly typed values. Type hints first appeared in Python 3.5, but because they’re based on comments, you can use them in any Python version.

This chapter focuses on the aforementioned three techniques for embedding documentation inside your code to make it more readable. External documentation, such as user manuals, online tutorials, and refer- ence materials, are important but not covered in this book. If you want to learn more about external documentation, check out the Sphinx documen- tation generator at https://www.sphinx-doc.org/.