Docstrings In Python

Docstrings In Python

Docstrings in Python are special text used to describe what a function, class, or module does in your Python code. They are written inside triple quotes and after the definition. Docstrings help you understand the purpose of the Python code without the need to read every line. Unlike regular comments, docstrings can be accessed using the help() function. Using the docstrings makes the code clean and readable. In this blog, you will learn the implementation, formatting, and application of docstrings in detail with examples.

Table Of Contents

What are Docstrings in Python?

In this section, you will be introduced to docstrings and how they differ from your general Python comments. Docstrings, or documentation strings, are literal strings that are kept as the first statement in a function, class, or module. Comments are completely ignored when the program runs, but docstrings are saved inside a special attribute called __doc__ and can be used in the program.

For Example:

Python

Output:

Docstrings in Python

Explanation: The function will print a greeting and return its documentation through the __doc__. This shows us that Python stores the docstrings for accessing and usage later. 

Why Use Docstrings in Python?

Docstrings in Python help you understand what every component of your code performs without going into the implementation. They will provide metadata for the tools for documentation and powerful IDE features, for example, hover-to-view help. It will also integrate seamless tools such as help() and pydoc.

Example:

Python

Output:

Why Use Docstrings in Python

Explanation: Here, the help function returns and displays the docstring along with the structured documentation without reading the source code.

Types of Python Docstrings

In this section, you will be informed regarding the various types of docstrings that the Python language supports for modules, functions, and classes.

1. Module Docstring in Python

The module-level docstring in Python describes the functionality provided by a Python file.

Example:

Python

Explanation: Here, Docstrings at the module level summarize the file’s purpose and are typically placed at the very top of the .py file. They can be accessed using the code import math_utils, and in the next line, write print(math_utils.__doc__).

2. Function/Method Docstrings

The function in Docstrings defines what the function does, expected parameters, return values, and exceptions.

For example:

Python

Output:

Function Method Docstrings

Explanation: Here, the function would include a properly formatted docstring with detailed inputs, outputs, and the function’s core purpose.

3. Class Docstrings in Python

The class docstrings in Python help to describe the role and the capabilities of the class.

Example:

Python

Output:

Class Docstrings

Explanation: Here, the class and the method docstrings both can be retrieved, giving context at both structural levels.

Features of Docstrings in Python

This section outlines the capabilities of utilizing docstrings and the advantages of using docstrings over traditional comments in Python.

  • Multiline and Structured: Triple quotes allow line breaks, giving freedom to write detailed explanations.
  • Runtime Accessibility: Docstrings are stored in __doc__ and can be retrieved using introspection tools.
  • Documentation Tool Integration: Tools in Python, with the likes of Sphinx, pdoc, and help(), can parse and display docstrings.
  • Support for Formatting Styles: Formats like Google style, NumPy style, and reStructuredText provide consistency.
  • Useful in IDEs: Most modern IDEs show docstrings in tooltips, making them immediately useful during development.

Comparison Table Between Docstrings and Comments in Python

Here is a table that will help you distinguish between them.

FeatureDocstringsComments
PurposeIt is used to define the functionality of modules, functions, and classes in a structured format.It is used to define logic or leave notes in code without affecting execution.
SyntaxDocstring is enclosed in triple quotes like this “””Docstring””” Comments start with a # symbol.
ScopeIt is associated with classes, modules, and functions and is meant to be accessed programmatically.Comments are limited to inline usage and are not accessible during runtime.
Tooling supportUsed by tools like help(), IDEs, and documentation generators.Comments are not produced by such tools.
Best forWhen you need to document the “what and why” of your code in a user-facing manner.Provides implementation notes, to-dos, internal logic clarification, etc.

Use Cases for Docstrings in Python

In the section below, you will be shown use cases to implement in your coding sessions.

Use case 1 (To document a data validation utility)

We can utilize docstrings in utility functions that get reused often. Here’s an example of such validation that checks if an input is a valid email.

Example:

Python

Output:

To document a data validation utility

Explanation: You use the docstring here to describe input expectations (a string), output type (bool), and even provide testable examples. This helps both manual readers and auto-generated documentation tools understand the utility instantly.

Use case 2 (Defining a custom class for logging)

Attempting to define a class that is meant to be reused (e.g., a logger), having structured docstrings at the class and method level can ensure clarity on how you can use it and what each method does.

Example:

Python

Output:

Defining a custom class for logging

Explanation: 

Here, the use case shows you how docstrings can help in guiding you to instantiate a class, what parameters you are meant to pass, and how to implement each method. Docstrings also explain internal attributes for both the class and its methods, which can be useful for advanced usage or extension.

Use of docstring in this use case:

The main utility of docstrings in this case is to outline class attributes, construct parameters, and method behaviors, making it quite easy for someone to adopt it with minimal effort.

Best Practices to Implement Python Docstrings

Try to be clear and concise: It is better to begin with a summary in a single line, which is followed by more details if necessary.

Utilize triple quotes for multiline docstrings: Even in the case of the string being short, stick to the triple quotes for consistency and clarity.

Keep following a style guide: Better to pick a format like Google or NumPy style and use it across your codebase.

Keep documentation of parameters and return types: It makes your code self-documenting by stating the expected input/output explicitly.

Try to include examples when useful: Keep in mind to add usage examples to the docstring.

Conclusion

Docstrings are an essential part of Python that allows you to add readable text to your code. They describe what a function, class, or module does, which helps in making your code easier to understand. Unlike comments, docstrings are saved in memory and work with tools like help() and pydoc. Docstrings are very helpful when a group of people is working and modifying the same code. Proper docstrings make your code better, help avoid mistakes, and make it easier for others, including you, to understand and use. Further, upgrade your Python skills by visiting a Python certification course, and get ready to excel in your career with Basic Python interview questions prepared by experts.

Docstrings In Python-FAQs

Q1. What if we use docstrings for the single-line documentation in the Python language?

Yes, we would have to ensure it is enclosed in triple quotes, which in turn will ensure compatibility with tools and standardization.

Q2. Are docstrings capable of affecting my performance?

The Docstrings are stored once per function/module/class and can only be accessed if it is explicitly requested. Hence, they do not affect performance.

Q3. When working in Python, are docstrings usually mandatory?

Language might not need them, but it is still best practice, considering production code and libraries.

Q4. How will docstrings be able to interact with IDEs and help tools?

Most modern IDEs display docstrings as pop-up documentation during coding. Tools like help() also show them in interactive shells.  

Q5. Will passing docstrings make the code capable of documenting exceptions and examples?

Yes. You can and should include sections for exceptions raised and usage examples using formats like Google or NumPy style.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner