- Aliases
- and operator
- Booleans
- Classes
- Code blocks
- Comments
- Conditional statements
- Console
- Data structures
- datetime module
- Decorator
- Dictionaries
- Docstrings
- enum
- enumerate() function
- Equality operator
- Exception handling
- False
- File handling
- Floats
- For loops
- Formatted strings
- Functions
- Generator
- Greater than operator
- Greater than or equal to operator
- If statement
- in operator
- Indices
- Inequality operator
- Integers
- Iterator
- Lambda function
- Less than operator
- Less than or equal to operator
- List append() method
- List comprehension
- List insert() method
- List pop() method
- List sort() method
- Lists
- Logging
- map() function
- Match statement
- Math module
- Modules
- Multiprocessing
- Multithreading
- None
- not operator
- OOP
- or operator
- Parameters
- print() function
- Random module
- range() function
- Recursion
- Regular expressions
- requests Library
- return statement
- round() function
- Sets
- SQLite
- String join() method
- String replace() method
- String split() method
- Strings
- time.sleep() function
- True
- try...except statement
- Tuples
- Variables
- While loops
- Zip function
PYTHON
Python Docstrings: Syntax, Usage, and Examples
Python docstrings are special string literals used to document functions, classes, and modules. Unlike regular comments, docstrings are stored as metadata and can be accessed programmatically using built-in tools like the help()
function.
How to Create Docstrings in Python
A docstring is written as a multi-line string enclosed in triple quotes (""" """
or ''' '''
). It should be placed immediately after the function, class, or module definition.
def greet(name):
"""Returns a greeting message with the provided name."""
return f"Hello, {name}!"
Docstrings should clearly describe what the function, class, or module does.
What Are Docstrings in Python?
Docstrings are documentation strings embedded within code. They help programmers understand the purpose and functionality of different code components without having to read through implementation details.
Python Docstrings Format
Python docstrings follow specific formatting conventions. The most common styles include:
- One-line docstrings (for simple functions)
- Multi-line docstrings (for more detailed explanations)
- Structured docstrings (following formats like Google style, NumPy style, or reStructuredText)
One-Line Docstring
Used when a function has a straightforward purpose.
def square(n):
"""Returns the square of a number."""
return n * n
Multi-Line Docstring
Used when a function requires a more detailed explanation.
def divide(a, b):
"""
Returns the result of dividing a by b.
Parameters:
a (int, float): The numerator.
b (int, float): The denominator.
Returns:
float: The division result.
"""
return a / b
Docstrings vs. Comments in Python
Both comments and docstrings help with documentation, but they serve different purposes:
| Feature | Comments (#
) | Docstrings (""" """
) |
| --- | --- | --- |
| Purpose | Explain code logic or disable code | Document modules, classes, and functions |
| Accessibility | Not accessible at runtime | Can be accessed using help()
|
| Placement | Anywhere in the code | Directly after definitions |
| Formatting | Uses #
before text | Uses triple quotes |
Example of a comment:
# This function calculates the square of a number
def square(n):
return n * n
Example of a docstring:
def square(n):
"""Returns the square of a number."""
return n * n
When to Use Docstrings in Python
Documenting Functions
Every function should have a docstring explaining its purpose, parameters, and return value.
def add(a, b):
"""Adds two numbers and returns the sum."""
return a + b
Documenting Classes
Docstrings in classes describe their attributes and methods.
class Car:
"""
Represents a car.
Attributes:
make (str): The car's brand.
model (str): The car's model.
year (int): The year of manufacture.
"""
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
Documenting Modules
Modules should include a docstring at the beginning to explain their purpose.
"""
math_utils.py
This module provides utility functions for mathematical operations.
"""
Examples of Using Docstrings in Python
Function Docstrings in Python
def factorial(n):
"""
Computes the factorial of a given number.
Parameters:
n (int): A non-negative integer.
Returns:
int: The factorial of n.
"""
if n == 0:
return 1
return n * factorial(n - 1)
Python Class Docstrings
class BankAccount:
"""
Represents a bank account with deposit and withdrawal functions.
Attributes:
balance (float): The current account balance.
"""
def __init__(self, initial_balance=0.0):
"""Initializes an account with a given balance."""
self.balance = initial_balance
def deposit(self, amount):
"""Adds money to the account."""
self.balance += amount
def withdraw(self, amount):
"""Removes money from the account if funds are available."""
if amount <= self.balance:
self.balance -= amount
Learn More About Python Docstrings
Generate Documentation from Python Docstrings
Docstrings can be used to generate documentation automatically using tools like:
pydoc
: Generates text-based documentation.Sphinx
: Generates professional-looking documentation in HTML or PDF format.
To generate documentation using pydoc
:
pydoc -w my_script.py
Difference Between Comments and Docstrings in Python
Comments provide short explanations but are ignored by tools that generate documentation. Docstrings, on the other hand, are structured documentation accessible at runtime.
Creating Documentation from Docstrings Python
Sphinx is commonly used for creating documentation. To use it:
pip install sphinx
sphinx-quickstart
Sphinx extracts docstrings and generates structured documentation.
How to Use Python Docstrings
To access a docstring, use the help()
function:
help(factorial)
This displays the function's documentation.
Docstrings in Python Example
Here's a full example of a documented module:
"""
temperature.py
This module provides functions for temperature conversion.
"""
def celsius_to_fahrenheit(celsius):
"""Converts Celsius to Fahrenheit."""
return (celsius * 9/5) + 32
def fahrenheit_to_celsius(fahrenheit):
"""Converts Fahrenheit to Celsius."""
return (fahrenheit - 32) * 5/9
Using help(temperature.celsius_to_fahrenheit)
will show the docstring for that function.
Python docstrings provide structured documentation for functions, classes, and modules. They differ from comments by being accessible at runtime. Using tools like pydoc
and Sphinx
, docstrings can be converted into readable documentation, making code easier to maintain and understand.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.