Python Docstrings
When writing Python programs, code readability is very important. One of the best ways to improve readability is by using docstrings.
Docstrings are used to describe:
- Functions
- Classes
- Modules
- Methods
They help developers understand what the code does without reading every line.
What is a Docstring?
A docstring is a special string used to document Python code.
It is written using triple quotes:
"""This is a docstring"""It is placed immediately after:
- Function definition
- Class definition
- Module header
Why Use Docstrings?
Docstrings help to:
- Explain code functionality
- Improve readability
- Support team collaboration
- Generate documentation automatically
- Make code easier to maintain
1. Function Docstrings
Example
def add(a, b):
"""Return the sum of two numbers."""
return a + bAccessing Docstring
print(add.__doc__)Output
Return the sum of two numbers.2. Multi-line Docstrings
def multiply(a, b):
"""
Multiply two numbers.
Parameters:
a (int): First number
b (int): Second number
Returns:
int: Product of a and b
"""
return a * b3. Class Docstrings
class Person:
"""
Represents a person with name and age.
"""
def __init__(self, name, age):
self.name = name
self.age = ageAccess Class Docstring
print(Person.__doc__)4. Module Docstrings
At the top of a Python file:
"""
This module provides basic arithmetic operations.
"""5. Method Docstrings
class Calculator:
def add(self, a, b):
"""Return sum of two numbers."""
return a + b6. Difference Between Comments and Docstrings
| Feature | Comments | Docstrings |
|---|---|---|
| Purpose | Explain code logic | Document code |
| Syntax | # comment | """docstring""" |
| Accessible | No | Yes |
| Used by tools | No | Yes |
7. Built-in help() Function
Python can display docstrings using help().
def greet():
"""Print greeting message."""
print("Hello")
help(greet)Output
Help on function greet:
greet()
Print greeting message.8. Google Style Docstrings
def divide(a, b):
"""
Divide two numbers.
Args:
a (int): numerator
b (int): denominator
Returns:
float: result of division
"""
return a / b9. NumPy Style Docstrings
def square(x):
"""
Square a number.
Parameters
----------
x : int
Input number
Returns
-------
int
Squared result
"""
return x * x10. Best Practices
- Always document public functions
- Keep docstrings concise
- Use triple double quotes
- Follow a consistent style
- Update docstrings when code changes
11. Common Mistakes
Missing Docstrings
def test():
return 1Fix:
Add documentation.
Writing unclear docstrings
Bad:
"""do stuff"""Good:
"""Return user age from database."""12. Real-World Applications
Docstrings are used in:
- API development
- Open-source projects
- Team collaboration
- Automated documentation tools (Sphinx)
- Code maintenance
Summary
Python docstrings are an essential part of writing clean and maintainable code. They help document functions, classes, and modules in a structured way that can be accessed programmatically.
Conclusion
Docstrings improve code quality by making Python programs easier to understand and maintain. By following good documentation practices, developers can build professional and scalable applications.


0 Comments