Python Code Documentation Best Practices

Python documentation pdf is not just a matter of readability or ease of access. It’s the way different teams work together to produce high quality end deliverables. Of course, this is heavily dependent on the team composition and their mindset with regards to software development particularly in its production aspects. Reader Guides – At the most basic level, Python Code Documentation is a document that helps us configure our system to be able to read and execute Python code from a specific location on our system’s hard drive. Ideally, we’d want this to be as straightforward as possible since we’re dealing with programmers here who may not be comfortable navigating through a system’s configuration settings. Fortunately, there are many tools out there that focus on automating this process to save us some legwork from testing, reading and modifying these configuration settings manually.

Are you new to Python programming? Do you want to learn the basics in the simplest way possible? You should start with the Python Code Documentation Best Practices course! In this course, we’ll start with a look at what it takes to get started, then we’ll cover some of the most important Python code documentation techniques in a step-by-step walkthrough.

Writing code is only half of the battle — doing it the right way is just as important. Exemplary documentation will make your life much, much easier. Python code documentation best practices gives you more time to focus on developing your algorithms and other parts of your projects. Let’s take a look at what makes good Python documentation — as well as some tips for making it even better.

This series goes over some of the best practices when writing code documentation. This video demonstrates how to write useful Python 3 code documentation in a consistent and informative way, then view that documentation by generating an HTML website directory out of it. The website is browsed with the Chrome browser, but any browser will do.

Why Documenting Your Code Is So Important

Hopefully, if you’re reading this tutorial, you already know the importance of documenting your code. But if not, then let me quote something Guido mentioned to me at a recent PyCon:

“Code is more often read than written.”

— Guido van Rossum

When you write code, you write it for two primary audiences: your users and your developers (including yourself). Both audiences are equally important. If you’re like me, you’ve probably opened up old codebases and wondered to yourself, “What in the world was I thinking?” If you’re having a problem reading your own code, imagine what your users or other developers are experiencing when they’re trying to use or contribute to your code.

Conversely, I’m sure you’ve run into a situation where you wanted to do something in Python and found what looks like a great library that can get the job done. However, when you start using the library, you look for examples, write-ups, or even official documentation on how to do something specific and can’t immediately find the solution.

After searching, you come to realize that the documentation is lacking or even worse, missing entirely. This is a frustrating feeling that deters you from using the library, no matter how great or efficient the code is. Daniele Procida summarized this situation best:

“It doesn’t matter how good your software is, because if the documentation is not good enough, people will not use it.

— Daniele Procida

In this guide, you’ll learn from the ground up how to properly document your Python code from the smallest of scripts to the largest of Python projects to help prevent your users from ever feeling too frustrated to use or contribute to your project.

Commenting vs Documenting Code

Before we can go into how to document your Python code, we need to distinguish documenting from commenting.

In general, commenting is describing your code to/for developers. The intended main audience is the maintainers and developers of the Python code. In conjunction with well-written code, comments help to guide the reader to better understand your code and its purpose and design:

“Code tells you how; Comments tell you why.”

— Jeff Atwood (aka Coding Horror)

Documenting code is describing its use and functionality to your users. While it may be helpful in the development process, the main intended audience is the users. The following section describes how and when to comment your code.

Basics of Commenting Code

Comments are created in Python using the pound sign (#) and should be brief statements no longer than a few sentences. Here’s a simple example:

def hello_world():
    # A simple comment preceding a simple print statement
    print("Hello World")

According to PEP 8, comments should have a maximum length of 72 characters. This is true even if your project changes the max line length to be greater than the recommended 80 characters. If a comment is going to be greater than the comment char limit, using multiple lines for the comment is appropriate:

def hello_long_world():
    # A very long statement that just goes on and on and on and on and
    # never ends until after it's reached the 80 char limit
    print("Hellooooooooooooooooooooooooooooooooooooooooooooooooooooooo World")

Commenting your code serves multiple purposes, including:

  • Planning and Reviewing: When you are developing new portions of your code, it may be appropriate to first use comments as a way of planning or outlining that section of code. Remember to remove these comments once the actual coding has been implemented and reviewed/tested:# First step # Second step # Third step
  • Code Description: Comments can be used to explain the intent of specific sections of code:# Attempt a connection based on previous settings. If unsuccessful, # prompt user for new settings.
  • Algorithmic Description: When algorithms are used, especially complicated ones, it can be useful to explain how the algorithm works or how it’s implemented within your code. It may also be appropriate to describe why a specific algorithm was selected over another.# Using quick sort for performance gains
  • Tagging: The use of tagging can be used to label specific sections of code where known issues or areas of improvement are located. Some examples are: BUGFIXME, and TODO.# TODO: Add condition for when val is None

Comments to your code should be kept brief and focused. Avoid using long comments when possible. Additionally, you should use the following four essential rules as suggested by Jeff Atwood:

  1. Keep comments as close to the code being described as possible. Comments that aren’t near their describing code are frustrating to the reader and easily missed when updates are made.
  2. Don’t use complex formatting (such as tables or ASCII figures). Complex formatting leads to distracting content and can be difficult to maintain over time.
  3. Don’t include redundant information. Assume the reader of the code has a basic understanding of programming principles and language syntax.
  4. Design your code to comment itself. The easiest way to understand code is by reading it. When you design your code using clear, easy-to-understand concepts, the reader will be able to quickly conceptualize your intent.

Remember that comments are designed for the reader, including yourself, to help guide them in understanding the purpose and design of the software.

Commenting Code via Type Hinting (Python 3.5+)

Type hinting was added to Python 3.5 and is an additional form to help the readers of your code. In fact, it takes Jeff’s fourth suggestion from above to the next level. It allows the developer to design and explain portions of their code without commenting. Here’s a quick example:

def hello_name(name: str) -> str:
    return(f"Hello {name}")

From examining the type hinting, you can immediately tell that the function expects the input name to be of a type str, or string. You can also tell that the expected output of the function will be of a type str, or string, as well. While type hinting helps reduce comments, take into consideration that doing so may also make extra work when you are creating or updating your project documentation.

Readability is a primary focus for Python developers, in both project and code documentation. Following some simple best practices can save both you and others a lot of time.

Project Documentation

README file at the root directory should give general information to both users and maintainers of a project. It should be raw text or written in some very easy to read markup, such as reStructuredText or Markdown. It should contain a few lines explaining the purpose of the project or library (without assuming the user knows anything about the project), the URL of the main source for the software, and some basic credit information. This file is the main entry point for readers of the code.

An INSTALL file is less necessary with Python. The installation instructions are often reduced to one command, such as pip install module or python setup.py install, and added to the README file.

LICENSE file should always be present and specify the license under which the software is made available to the public.

TODO file or a TODO section in README should list the planned development for the code.

CHANGELOG file or section in README should compile a short overview of the changes in the code base for the latest versions.

Project Publication

Depending on the project, your documentation might include some or all of the following components:

  • An introduction should give a very short overview of what can be done with the product, using one or two extremely simplified use cases. This is the thirty-second pitch for your project.
  • tutorial should show some primary use cases in more detail. The reader will follow a step-by-step procedure to set-up a working prototype.
  • An API reference is typically generated from the code (see docstrings). It will list all publicly available interfaces, parameters, and return values.
  • Developer documentation is intended for potential contributors. This can include code convention and general design strategy of the project.

Sphinx

Sphinx is far and away the most popular Python documentation tool. Use it. It converts reStructuredText markup language into a range of output formats including HTML, LaTeX (for printable PDF versions), manual pages, and plain text.

There is also greatfree hosting for your Sphinx docs: Read The Docs. Use it. You can configure it with commit hooks to your source repository so that rebuilding your documentation will happen automatically.

When run, Sphinx will import your code and using Python’s introspection features it will extract all function, method, and class signatures. It will also extract the accompanying docstrings, and compile it all into well structured and easily readable documentation for your project.

Python Documentation according to Best Practices

Every programming language supports documentation. Furthermore, every programming language has its own best practices when it comes to documentation. Python makes no exception, and we have some rules to follow when writing python documentation. In fact, the official Python website throws at you a list of things to do in this document. Probably not the easiest way to start writing documentation.

The most important concept you need to remember is that code and documentation must live in the same place. Writing the code and then creating a PDF document to explain its functionalities is a bad idea. Even more, it is one of the worst ideas we could have. By doing so, I guarantee that one day someone will edit the code and forget to update the document. This will create a gap between code and documentation that will eventually grow to make documentation useless.

Code and documentation must reside in the same place.

This is a modern concept of documentation, and many languages are adopting it. It simply means you write the documentation in the same file of the code. To be even more specific, you write the documentation inside the code you want to document. Documenting a function? Write its documentation inside the def statement. Documenting a class? Write the documentation inside the class statement, you get the point.

As we will see, Python does a really good job in that. Writing Python Documentation inside the code is ridiculously simple.

Writing Python Documentation

Introducing the docstring

Simply put, the docstring is a string containing the documentation of a given component. It is a special multiline string, thus you have to include it between three sets of quotes, not just one. Each individual component (a function, a class, a module) has its own docstring. If you don’t specify it, it will be None. Each component can have only one docstring.

The docstring is a string containing the documentation of a given component.

Writing a docstring is simple, you just add the multiline string syntax right after the definition statement. No blank lines before, no blank lines after. Take a look at the following code, it shows you how to write the docstring in any circumstance.”””This is the module docstring, as it is at the beginning of the file”””class SampleClass: “””This is the docstring for SampleClass”””def sample_method(self): “””This is the docstring for sample_method”””passdef sample_function: “””This is the docstring of sample_function”””pass

Dead simple. The docstring is not a comment, it is a string that the interpret will process. Furthermore, you can access the docstring with the __doc__ special attribute. If you want to print the documentation for SampleClass, you could print SampleClass.__doc__. If you want the one of sample_method, print SampleClass.sample_method.__doc__.

What to write inside a docstring

Writing Python documentation is extremely easy. However, writing meaningful python documentation requires more attention. You need to know what to write and what not to write.

Ideally, a docstring should explain what the function, class, or module does. It should not explain the way it works inside, but only how you can use the component from the outside. By reading the docstring, you should know how to use the function, class, or module it explains. You shouldn’t worry about how it works, only about how you can use it. Look at the following code.def multiply(a, b): “””Multiplies two numbers”””return a * b

We can change the code inside the function to perform a sequence of additions, rather than a simple multiplication. Nonetheless, the output will be the same, and so does the input. Thus, the docstring is still valid if we rewrite the function as below.def multiply(a, b): “””Multiplies two integers”””if a == 0 or b == 0: return 0 res = 0 for i in range(b): res += a return res

Now, it is true that this function will not work if b is negative, but we don’t care here. It is simply to show that docstring is useful when working outside the function.

Multiline Docstrings

Some components do serious stuff. They might perform advanced calculations, handle complex objects, and so on. For this kind of function, you might want to write a longer docstring. Not a problem, docstrings are natively multiline. However, you should write an overall description on a single line, leave a blank line, and then a more complex description.def multiply(a, b): “””Multiplies two integers The first number does not have constraints, but the second number cannot be negative. Doing otherwise leads to unexpected behaviour.”””if a == 0 or b == 0: return 0 res = 0 for i in range(b): res += a return res

More often than not, you will be writing multiline docstring. We will see why in a minute.

What does “documenting” mean?

Documenting means add information to your code for other programmers to read. If you took coding classes, someone probably told you that writing code means talking to the PC. If you believe that, think again, because computers only understand binary: 0 and 1.

You write code for people to read, not for computers.

Let this statement sink in your brain, as this can change the way you work. Even more, it can turn you from beginner to professional in no time, saving you all the pain in the road. You write code for people to read. It doesn’t matter if some other programmers will read your code, or if you are the only one working on it. At some point in time, you will have to read the code again. Thus, even if you are working alone, make a favor to the “you of the future”.

Documenting means adding an explanation to your code.

So, documenting means adding an explanation to your code. The program won’t use that for its functionality, but other programmers will use that to get by. Your should document every piece of code, even the ones you think obvious. Nothing is obvious when it comes to programming.

Conclusion

Documentation matters. Not only is it vital to any software project, but it also can help your program benefit from the positive reputation that comes with official documentation. How important is a good reputation? Glad you asked. The free software community has been waging an ongoing documentation war for years. That’s right, folks — we are fighting over how people perceive our work by simply giving them proper documentation or not. Reputation and perception matter because public opinion can make or break your programming efforts.

It is understandable that developers are spending longer hours on delivering high-quality and bug-free code. The reason can be attributed to the fact that they don’t want to give anything less than perfect output. Advertising money is one of the key reasons, especially when it comes to the python project documentation pdf which has a significant role in gaining profit. In such case, developers strive hard to make sure their output is faultless and free of bugs.

Leave a Comment