When implementing a function, a class or a module, it is important to include a documentation so that it will be easier to understand and maintain in future. Most people tend to overlook this part as they may regard it as trivial or time-consuming. While this may seem okay for simple programs, it can easily become a readability barrier if the program becomes more complex and involves more than just a single developer. You should write programs with your future self in mind, you do not want to write a class and returning six months later, you can't easily remember how it works or what purpose it is intended to accomplish.
Documenting functions and other objects offers the following advantages:
- Boosts code readability making it easier to understand its usage and purpose.
- Makes it easy to maintain the code.
- Makes it easy for IDEs and editors to assist in debugging.
Python offers a very convenient way for writing documentations through the use of docstrings.
What are docstrings?
A docstring is simply a string written using the triple quotes format, that appears as the first statement in a function, a method, a class or a module. It should, at least, give a quick summary of the object's usage and purpose.
Consider the following example.
As shown in the above example, Python automatically assigns our docstring to the __doc__
attribute. We can use this attribute to conveniently retrieve the docstring of an object. In the following examples we retrieve the docstrings of some builtin functions.
access the docstring with the help() Function
The docstring is also included in the help message when we call the help()
function. However, the help()
function includes other details about the target object that may have nothing to do with the docstrings.
Docstring in classes
With classes, the documentation text should summarize the behavior of the class, list the public methods and attributes and also include any other text that may help someone understand the class better. Each of the public methods should also contain their own docstrings.
A class to represent a dog.
...
attributes
----------
name: str
name of the dog
owner: str
name of the dog owner.
age: int
age of the dog.
methods
------------
get_info() -> str:
Print information about the dog i.e name, age, and owner
Docstring in modules and packages
For modules/scripts, the docstring appears as the first statement at the top of the file. It should offer general information about the functions and classes defined there. The following example demonstrates this with a module defined in the standard library.
With packages, the docstring is written at the top of the __init__.py
file.