
- Python - Home
- Python - Overview
- Python - History
- Python - Features
- Python vs C++
- Python - Hello World Program
- Python - Application Areas
- Python - Interpreter
- Python - Environment Setup
- Python - Virtual Environment
- Python - Basic Syntax
- Python - Variables
- Python - Data Types
- Python - Type Casting
- Python - Unicode System
- Python - Literals
- Python - Operators
- Python - Arithmetic Operators
- Python - Comparison Operators
- Python - Assignment Operators
- Python - Logical Operators
- Python - Bitwise Operators
- Python - Membership Operators
- Python - Identity Operators
- Python - Operator Precedence
- Python - Comments
- Python - User Input
- Python - Numbers
- Python - Booleans
- Python - Control Flow
- Python - Decision Making
- Python - If Statement
- Python - If else
- Python - Nested If
- Python - Match-Case Statement
- Python - Loops
- Python - for Loops
- Python - for-else Loops
- Python - While Loops
- Python - break Statement
- Python - continue Statement
- Python - pass Statement
- Python - Nested Loops
- Python Functions & Modules
- Python - Functions
- Python - Default Arguments
- Python - Keyword Arguments
- Python - Keyword-Only Arguments
- Python - Positional Arguments
- Python - Positional-Only Arguments
- Python - Arbitrary Arguments
- Python - Variables Scope
- Python - Function Annotations
- Python - Modules
- Python - Built in Functions
- Python Strings
- Python - Strings
- Python - Slicing Strings
- Python - Modify Strings
- Python - String Concatenation
- Python - String Formatting
- Python - Escape Characters
- Python - String Methods
- Python - String Exercises
- Python Lists
- Python - Lists
- Python - Access List Items
- Python - Change List Items
- Python - Add List Items
- Python - Remove List Items
- Python - Loop Lists
- Python - List Comprehension
- Python - Sort Lists
- Python - Copy Lists
- Python - Join Lists
- Python - List Methods
- Python - List Exercises
- Python Tuples
- Python - Tuples
- Python - Access Tuple Items
- Python - Update Tuples
- Python - Unpack Tuples
- Python - Loop Tuples
- Python - Join Tuples
- Python - Tuple Methods
- Python - Tuple Exercises
- Python Sets
- Python - Sets
- Python - Access Set Items
- Python - Add Set Items
- Python - Remove Set Items
- Python - Loop Sets
- Python - Join Sets
- Python - Copy Sets
- Python - Set Operators
- Python - Set Methods
- Python - Set Exercises
- Python Dictionaries
- Python - Dictionaries
- Python - Access Dictionary Items
- Python - Change Dictionary Items
- Python - Add Dictionary Items
- Python - Remove Dictionary Items
- Python - Dictionary View Objects
- Python - Loop Dictionaries
- Python - Copy Dictionaries
- Python - Nested Dictionaries
- Python - Dictionary Methods
- Python - Dictionary Exercises
- Python Arrays
- Python - Arrays
- Python - Access Array Items
- Python - Add Array Items
- Python - Remove Array Items
- Python - Loop Arrays
- Python - Copy Arrays
- Python - Reverse Arrays
- Python - Sort Arrays
- Python - Join Arrays
- Python - Array Methods
- Python - Array Exercises
- Python File Handling
- Python - File Handling
- Python - Write to File
- Python - Read Files
- Python - Renaming and Deleting Files
- Python - Directories
- Python - File Methods
- Python - OS File/Directory Methods
- Python - OS Path Methods
- Object Oriented Programming
- Python - OOPs Concepts
- Python - Classes & Objects
- Python - Class Attributes
- Python - Class Methods
- Python - Static Methods
- Python - Constructors
- Python - Access Modifiers
- Python - Inheritance
- Python - Polymorphism
- Python - Method Overriding
- Python - Method Overloading
- Python - Dynamic Binding
- Python - Dynamic Typing
- Python - Abstraction
- Python - Encapsulation
- Python - Interfaces
- Python - Packages
- Python - Inner Classes
- Python - Anonymous Class and Objects
- Python - Singleton Class
- Python - Wrapper Classes
- Python - Enums
- Python - Reflection
- Python Errors & Exceptions
- Python - Syntax Errors
- Python - Exceptions
- Python - try-except Block
- Python - try-finally Block
- Python - Raising Exceptions
- Python - Exception Chaining
- Python - Nested try Block
- Python - User-defined Exception
- Python - Logging
- Python - Assertions
- Python - Built-in Exceptions
- Python Multithreading
- Python - Multithreading
- Python - Thread Life Cycle
- Python - Creating a Thread
- Python - Starting a Thread
- Python - Joining Threads
- Python - Naming Thread
- Python - Thread Scheduling
- Python - Thread Pools
- Python - Main Thread
- Python - Thread Priority
- Python - Daemon Threads
- Python - Synchronizing Threads
- Python Synchronization
- Python - Inter-thread Communication
- Python - Thread Deadlock
- Python - Interrupting a Thread
- Python Networking
- Python - Networking
- Python - Socket Programming
- Python - URL Processing
- Python - Generics
- Python Libraries
- NumPy Tutorial
- Pandas Tutorial
- SciPy Tutorial
- Matplotlib Tutorial
- Django Tutorial
- OpenCV Tutorial
- Python Miscellenous
- Python - Date & Time
- Python - Maths
- Python - Iterators
- Python - Generators
- Python - Closures
- Python - Decorators
- Python - Recursion
- Python - Reg Expressions
- Python - PIP
- Python - Database Access
- Python - Weak References
- Python - Serialization
- Python - Templating
- Python - Output Formatting
- Python - Performance Measurement
- Python - Data Compression
- Python - CGI Programming
- Python - XML Processing
- Python - GUI Programming
- Python - Command-Line Arguments
- Python - Docstrings
- Python - JSON
- Python - Sending Email
- Python - Further Extensions
- Python - Tools/Utilities
- Python - GUIs
- Python Advanced Concepts
- Python - Abstract Base Classes
- Python - Custom Exceptions
- Python - Higher Order Functions
- Python - Object Internals
- Python - Memory Management
- Python - Metaclasses
- Python - Metaprogramming with Metaclasses
- Python - Mocking and Stubbing
- Python - Monkey Patching
- Python - Signal Handling
- Python - Type Hints
- Python - Automation Tutorial
- Python - Humanize Package
- Python - Context Managers
- Python - Coroutines
- Python - Descriptors
- Python - Diagnosing and Fixing Memory Leaks
- Python - Immutable Data Structures
- Python Useful Resources
- Python - Questions & Answers
- Python - Interview Questions & Answers
- Python - Online Quiz
- Python - Quick Guide
- Python - Reference
- Python - Cheatsheet
- Python - Projects
- Python - Useful Resources
- Python - Discussion
- Python Compiler
- NumPy Compiler
- Matplotlib Compiler
- SciPy Compiler
Python - Docstrings
Docstrings in Python
In Python, docstrings are a way of documenting modules, classes, functions, and methods. They are written within triple quotes (""" """) and can span multiple lines.
Docstrings serve as convenient way of associating documentation with Python code. They are accessible through the __doc__ attribute of the respective Python objects they document. Below are the different ways to write docstrings −
Single-Line Docstrings
Single-line docstrings are used for brief and simple documentation. They provide a concise description of what the function or method does. Single-line docstrings should fit on one line within triple quotes and end with a period.
Example
In the following example, we are using a single line docstring to write a text −
def add(a, b): """Return the sum of two numbers.""" return a + b result = add(5, 3) print("Sum:", result)
Multi-Line Docstrings
Multi-line docstrings are used for more detailed documentation. They provide a more comprehensive description, including the parameters, return values, and other relevant details. Multi-line docstrings start and end with triple quotes and include a summary line followed by a blank line and a more detailed description.
Example
The following example uses multi-line docstrings as an explanation of the code −
def multiply(a, b): """ Multiply two numbers and return the result. Parameters: a (int or float): The first number. b (int or float): The second number. Returns: int or float: The result of multiplying a and b. """ return a * b result = multiply(5, 3) print("Product:", result)
Docstrings for Modules
When writing docstrings for modules, place the docstring at the top of the module, right after any import statements. The module docstring provide an overview of the module's functionality and list its primary components, such as list of functions, classes, and exceptions provided by the module.
Example
In this example, we demonstrate the use of docstrings for modules in Python −
import os """ This module provides Utility functions for file handling operations. Functions: - 'read_file(filepath)': Reads and returns the contents of the file. - 'write_file(filepath, content)': Writes content to the specified file. Classes: - 'FileNotFoundError': Raised when a file is not found. Example usage: >>> import file_utils >>> content = file_utils.read_file("example.txt") >>> print(content) 'Hello, world!' >>> file_utils.write_file("output.txt", "This is a test.") """ print("This is os module")
Docstrings for Classes
Classes can have docstrings to describe their purpose and usage. Each method within the class can also have its own docstring. The class docstring should provide an overview of the class and its methods.
Example
In the example below, we showcase the use of docstrings for classes in Python −
class Calculator: """ A simple calculator class to perform basic arithmetic operations. Methods: - add(a, b): Return the sum of two numbers. - multiply(a, b): Return the product of two numbers. """ def add(self, a, b): """Return the sum of two numbers.""" return a + b def multiply(self, a, b): """ Multiply two numbers and return the result. Parameters: a (int or float): The first number. b (int or float): The second number. Returns: int or float: The result of multiplying a and b. """ return a * b cal = Calculator() print(cal.add(87, 98)) print(cal.multiply(87, 98))
Accessing Docstrings
Docstrings in Python are accessed using the __doc__ attribute of the object they document. This attribute contains the documentation string (docstring) associated with the object, providing a way to access and display information about the purpose and usage of functions, classes, modules, or methods.
Example
In the following example, we are defining two functions, "add" and "multiply", each with a docstring describing their parameters and return values. We then use the "__doc__" attribute to access and print these docstrings −
# Define a function with a docstring def add(a, b): """ Adds two numbers together. Parameters: a (int): The first number. b (int): The second number. Returns: int: The sum of a and b. """ return a + b result = add(5, 3) print("Sum:", result) # Define another function with a docstring def multiply(x, y): """ Multiplies two numbers together. Parameters: x (int): The first number. y (int): The second number. Returns: int: The product of x and y. """ return x * y result = multiply(4, 7) print("Product:", result) # Accessing the docstrings print(add.__doc__) print(multiply.__doc__)
Best Practices for Writing Docstrings
Following are the best practices for writing docstrings in Python −
Be Clear and Concise − Ensure the docstring clearly explains the purpose and usage of the code, avoiding unnecessary details.
Use Proper Grammar and Spelling − Ensure the docstring is well-written with correct grammar and spelling.
Follow Conventions − Use the standard conventions for formatting docstrings, such as the Google style, NumPy style, or Sphinx style.
Include Examples − Provide examples where applicable to illustrate how to use the documented code.
Google Style Docstring
Google style docstrings provide a structured way to document Python code using indentation and headings. They are designed to be readable and informative, following a specific format.
Example
Following is an example of a function with a Google style docstring −
def divide(dividend, divisor): """ Divide two numbers and return the result. Args: dividend (float): The number to be divided. divisor (float): The number to divide by. Returns: float: The result of the division. Raises: ValueError: If `divisor` is zero. """ if divisor == 0: raise ValueError("Cannot divide by zero") return dividend / divisor result = divide(4, 7) print("Division:", result)
NumPy/SciPy Style Docstring
NumPy/SciPy style docstrings are common in scientific computing. They include sections for parameters, returns, and examples.
Example
Following is an example of a function with a NumPy/SciPy style docstring −
def fibonacci(n): """ Compute the nth Fibonacci number. Parameters ---------- n : int The index of the Fibonacci number to compute. Returns ------- int The nth Fibonacci number. Examples -------- >>> fibonacci(0) 0 >>> fibonacci(5) 5 >>> fibonacci(10) 55 """ if n == 0: return 0 elif n == 1: return 1 else: return fibonacci(n-1) + fibonacci(n-2) result = fibonacci(4) print("Result:", result)
Sphinx Style Docstring
Sphinx style docstrings are compatible with the Sphinx documentation generator and use reStructuredText formatting.
The reStructuredText (reST) is a lightweight markup language used for creating structured text documents. The Sphinx documentation generator takes "reStructuredText" files as input and generates high-quality documentation in various formats, including HTML, PDF, ePub, and more.
Example
Following is an example of a function with a Sphinx style docstring −
def divide(dividend, divisor): """ Divide two numbers and return the result. Args: dividend (float): The number to be divided. divisor (float): The number to divide by. Returns: float: The result of the division. Raises: ValueError: If `divisor` is zero. """ if divisor == 0: raise ValueError("Cannot divide by zero") return dividend / divisor result = divide(76, 37) print("Result:", result)
Docstring vs Comment
Following are the differences highlighted between Python docstrings and comments, focusing on their purposes, formats, usages, and accessibility respectively −
Docstring | Comment |
---|---|
Used to document Python objects such as functions, classes, methods, modules, or packages. | Used to annotate code for human readers, provide context, or temporarily disable code. |
Written within triple quotes (""" """ or ''' ''') and placed immediately after the object's definition. | Start with the # symbol and are placed on the same line as the annotated code. |
Stored as an attribute of the object and accessible programmatically. | Ignored by the Python interpreter during execution, purely for human understanding. |
Accessed using the __doc__ attribute of the object. | Not accessible programmatically; exists only in the source code. |