PEP 257, which is the guide for writing docstrings in Python.
A docstring is a short piece of text inside quotes that explains what a module, function, class, or method does.
It helps other people read your code.
It also helps you understand your code later.
Step 1: What is a docstring?
A docstring is a string written as the first line inside:
- a module
- a function
- a class
- a method
Example:
def add_numbers(a, b):
"""Return the sum of two numbers."""
return a + b
Here:
"""Return the sum of two numbers."""
is the docstring.
It explains what the function does.
Step 2: Why do we use docstrings?
Docstrings are used to:
- explain code clearly
- make code easier to read
- help other programmers
- help tools generate documentation automatically
- make your program more professional
So, docstrings are like instructions or explanations inside the code.
Step 3: What does PEP 257 try to do?
PEP 257 gives standard rules for writing docstrings.
It tells you:
- what a docstring should contain
- where to put it
- how to format it
It is a convention, not a strict law.
That means you should follow it for clean code, but Python will still run if you do not.
Step 4: Where should docstrings be written?
According to PEP 257:
Modules should have docstrings
A module is a Python file.
Example:
"""This module contains math helper functions."""
Functions should have docstrings
Example:
def greet():
"""Print a greeting message."""
Classes should have docstrings
Example:
class Student:
"""Represent a student."""
Public methods should have docstrings
That includes __init__.
Example:
class Student:
def __init__(self, name):
"""Initialize the student with a name."""
self.name = name
So the main idea is:
if the code is meant to be used by people, it should usually have a docstring.
Step 5: Always use triple double quotes
PEP 257 says to use:
"""docstring"""
Not single quotes like this:
'docstring'
Not triple single quotes like this:
'''docstring'''
The recommended style is always:
"""docstring"""
Why?
Because:
- it is the standard style
- it is easy to expand later
- it keeps code consistent
If your docstring contains backslashes, you may use raw string format:
r"""This path is C:\new_folder\test"""
Step 6: There are two types of docstrings
PEP 257 says there are two forms:
- one-line docstrings
- multi-line docstrings
Step 7: One-line docstrings
Use a one-line docstring when the meaning is simple and short.
Example:
def get_name():
"""Return the user's name."""
Important rules for one-line docstrings
Rule 1: Use triple double quotes
Even if the sentence is short.
Rule 2: Keep opening and closing quotes on the same line
Like this:
"""Return the user's name."""
Rule 3: No blank line before or after
Write it directly under the function line.
Rule 4: End with a period
Good:
"""Return the user's name."""
Bad:
"""Return the user's name"""
Rule 5: Write it like a command
PEP 257 prefers command style.
Good:
"""Return the user's name."""
Not preferred:
"""Returns the user's name."""
So use words like:
- Return
- Calculate
- Create
- Open
Step 8: Do not repeat the function signature
Do not write docstrings like this:
def add(a, b):
"""add(a, b) -> int"""
Why is this bad?
Because Python already shows the function name and parameters.
You do not need to repeat them.
Instead, explain what it does.
Better:
def add(a, b):
"""Return the sum of two numbers."""
Step 9: Multi-line docstrings
Use a multi-line docstring when the explanation needs more detail.
Example:
def divide(a, b):
"""Divide one number by another.
Return the result of a divided by b.
Raise an error if b is zero.
"""
return a / b
Step 10: Structure of a multi-line docstring
A multi-line docstring has 3 parts:
Part 1: Summary line
This is the first short line.
Example:
"""Divide one number by another.
Part 2: Blank line
Leave one empty line after the summary.
Part 3: More explanation
Then give more detail.
Example:
def divide(a, b):
"""Divide one number by another.
Return the result of a divided by b.
Raise an error if b is zero.
"""
This format is important because tools may use the first line as a summary.
Step 11: Closing quotes in multi-line docstrings
If the docstring is more than one line, put the closing quotes on their own line.
Correct:
def divide(a, b):
"""Divide one number by another.
Return the result of a divided by b.
"""
Not preferred:
def divide(a, b):
"""Divide one number by another.
Return the result of a divided by b."""
The first style is cleaner.
Step 12: Docstring for a script
If your Python file is a script that runs from the command line, its docstring should explain:
- what the script does
- how to run it
- what arguments it needs
- what files or environment variables it uses
That means the docstring can work like a help message.
For example:
"""Calculate the total cost of items.
Usage:
python total.py
"""
So a script docstring should help a new user understand the program.
Step 13: Docstring for a module
A module docstring should explain what the whole file contains.
Example:
"""Provide utility functions for math operations.
Functions:
- add_numbers: Return the sum of two numbers.
- subtract_numbers: Return the difference of two numbers.
"""
So the module docstring gives an overview of the file.
Step 14: Docstring for a function or method
A function docstring should explain:
- what the function does
- its arguments
- its return value
- side effects if any
- exceptions if any
- restrictions if any
Example:
def divide(a, b):
"""Divide one number by another.
Args:
a: The number to be divided.
b: The divisor.
Returns:
The result of a divided by b.
Raises:
ZeroDivisionError: If b is zero.
"""
PEP 257 does not force one exact format like Args: or Returns:, but it says these things should be documented when needed.
Step 15: Docstring for a class
A class docstring should explain:
- what the class represents
- what it does
- its public methods
- its important variables
Example:
class Student:
"""Represent a student with a name and ID."""
If the class is intended for inheritance, the docstring should also explain what subclasses need to know.
Step 16: The __init__ method also needs a docstring
The constructor should also have its own docstring.
Example:
class Student:
"""Represent a student."""
def __init__(self, name, student_id):
"""Initialize the student with a name and ID."""
self.name = name
self.student_id = student_id
Step 17: If a class inherits from another class
If a class mostly uses behavior from a parent class, the docstring should mention that.
If a method completely replaces the parent method, use the word:
- override
If a method uses the parent method and adds extra behavior, use the word:
- extend
This helps people understand inheritance clearly.
Step 18: How to document arguments
PEP 257 says argument names should be written using their real names.
Do not write them in all capital letters in normal text.
Bad style:
"""REAL is the real part."""
Better:
"""real is the real part."""
Because Python is case-sensitive, the real parameter names matter.
Example:
def complex_number(real=0.0, imag=0.0):
"""Form a complex number.
Keyword arguments:
real -- the real part
imag -- the imaginary part
"""
Step 19: Blank line after class docstrings
For class docstrings, leave a blank line between the docstring and the first method.
Example:
class Dog:
"""Represent a dog."""
def bark(self):
"""Print a barking sound."""
print("Woof")
This makes the code easier to read.
Step 20: Indentation matters
In multi-line docstrings, indentation should be neat and consistent.
Example:
def hello():
"""Say hello.
Print a greeting to the screen.
"""
print("Hello")
The text inside the docstring is indented to match the function body.
Step 21: What happens to indentation internally?
Python keeps the spaces inside the docstring.
But tools can remove extra common indentation when reading it.
That is why proper indentation is important.
Example:
def foo():
"""
This is a docstring.
"""
Even though there are spaces before "This is a docstring.", tools can trim them.
So the meaning becomes:
This is a docstring.
The PEP includes code showing how tools remove extra indentation.
You do not need to memorize that code.
The important idea is:
Write docstrings neatly and consistently.
Step 22: One-line vs multi-line example
These both mean the same thing after trimming:
def foo():
"""A multi-line
docstring.
"""
and
def bar():
"""
A multi-line
docstring.
"""
Both are acceptable, but the format must stay clean.
Step 23: Main rules you should remember
Here is the easiest summary:
For every docstring:
-
use
"""triple double quotes""" - place it as the first statement
- write clearly
- use simple explanation
- end one-line summary with a period
For one-line docstrings:
- keep all quotes on one line
- write a short command sentence
Example:
"""Return the total price."""
For multi-line docstrings:
- start with a short summary line
- leave one blank line
- add more explanation below
-
put closing
"""on its own line
Step 24: Good and bad examples
Good one-line docstring
def greet(name):
"""Return a greeting message."""
return "Hello, " + name
Bad one-line docstring
def greet(name):
"""Returns greeting"""
return "Hello, " + name
Why bad?
- not command style
- no period
- too vague
Good multi-line docstring
def greet(name):
"""Return a greeting message.
Take a user's name and return a polite greeting.
"""
return "Hello, " + name
Bad signature-style docstring
def greet(name):
"""greet(name)"""
return "Hello, " + name
Why bad?
Because it only repeats the function name and parameter.
Step 25: Very simple meaning of PEP 257
PEP 257 is telling you:
Write docstrings in a clean, standard, readable way so everyone can understand your code.
That is the whole goal.
Step 26: Easy template you can follow
Function template
def function_name(parameter1, parameter2):
"""Do something useful.
Explain what the function does.
Explain important parameters if needed.
Explain what it returns if needed.
"""
Class template
class ClassName:
"""Represent something important."""
def __init__(self, value):
"""Initialize the object with a value."""
self.value = value
Module template
"""Describe what this module does.
This module contains helper functions for ...
"""
Step 27: Difference between PEP 8 and PEP 257
You mentioned both PEP 8 and PEP 257.
PEP 8
PEP 8 is the general style guide for Python code.
It covers things like:
- indentation
- spaces
- line length
- naming
- formatting
PEP 257
PEP 257 is specifically about docstrings.
It explains how to write documentation strings correctly.
So:
- PEP 8 = code style
- PEP 257 = docstring style
Step 28: Final simple summary
Here is the shortest simple summary:
- A docstring explains code.
- Put it as the first line inside a module, function, class, or method.
-
Use triple double quotes:
""" """ - One-line docstrings should be short and end with a period.
-
Write docstrings like commands, such as
"Return the total." - Do not repeat the function signature.
-
Multi-line docstrings need:
- a summary line
- a blank line
- more detail
- Class, function, and module docstrings make code easier to read and maintain.
No comments:
Post a Comment