Python Docstrings

In Python, a docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. Docstrings are used to provide documentation for your code and help users understand its purpose, usage, and functionality. They can be accessed using the . __doc__ attribute of the object.

Here's how docstrings work with examples:

Module Docstrings

A docstring at the beginning of a module provides an overview of the module's purpose, functionality, and usage.

"""This module provides functions to perform mathematical operations.""" def add(a, b): """Add two numbers and return the result.""" return a + b def subtract(a, b): """Subtract one number from another and return the result.""" return a - b

Function Docstrings

A docstring inside a function describes what the function does, its parameters, and return values.

def multiply(a, b): """Multiply two numbers and return the product.""" return a * b

Class Docstrings

A docstring for a class should describe its purpose, attributes, methods, and usage.

class Calculator: """A simple calculator class.""" def __init__(self): """Initialize the Calculator instance.""" self.result = 0 def add(self, num): """Add a number to the current result.""" self.result += num

Method Docstrings

Similar to function docstrings, method docstrings explain the purpose and usage of methods within a class.

class Circle: """A class representing a circle.""" def __init__(self, radius): """Initialize the Circle instance with a given radius.""" self.radius = radius def area(self): """Calculate and return the area of the circle.""" return 3.14 * self.radius ** 2

You can access the docstrings using the .__doc__ attribute:

print(add.__doc__) print(Calculator.__doc__) print(Calculator.add.__doc__) print(Circle.__doc__) print(Circle.area.__doc__)

It's important to write clear and informative docstrings to make your code more readable and accessible to other developers. You can also generate documentation using tools like Sphinx based on docstrings.


Python docstrings are string literals placed as the first statement in modules, functions, classes, and methods to provide documentation for code. They help users understand the purpose, functionality, parameters, and usage of different elements in the codebase. Docstrings can be accessed using the . __doc__ attribute and are a crucial tool for creating clear and informative documentation for Python programs.