A "document statement" in Python is actually called a docstring. It's a string literal that occurs as the first statement in a module, function, class, or method definition. Its purpose is to document the code and provide a concise summary of its functionality.
Here's how to use a docstring in a Python function, along with its benefits:
How to Use a Docstring in a Python Function
Place the docstring immediately after the def
line and before any other code within the function. It should be enclosed in triple quotes ("""Docstring goes here"""
or '''Docstring goes here'''
). Triple double-quotes are generally preferred.
Example:
def add_numbers(a, b):
"""
This function takes two numbers as input and returns their sum.
Args:
a (int or float): The first number.
b (int or float): The second number.
Returns:
int or float: The sum of the two input numbers.
Raises:
TypeError: If 'a' or 'b' are not numbers.
"""
if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
raise TypeError("Both inputs must be numbers.")
return a + b
def greet(name):
"""
Greets the user by name.
Args:
name (str): The name of the person to greet.
Returns:
str: A greeting message.
"""
return f"Hello, {name}!"
Key Aspects and Benefits of Docstrings:
Placement:
It must be the very first statement inside the function definition (or class/module). If you put any other statement before it, it won't be recognized as a docstring.
Accessing Docstrings:
You can access the docstring of a function (or any object with a docstring) using its
__doc__
attribute:Pythonprint(add_numbers.__doc__) # Output: # This function takes two numbers as input and returns their sum. # # Args: # a (int or float): The first number. # b (int or float): The second number. # # Returns: # int or float: The sum of the two input numbers. # # Raises: # TypeError: If 'a' or 'b' are not numbers.
You can also use the built-in
help()
function, which is a great way to view documentation in the interactive interpreter:Pythonhelp(add_numbers) # Output will show the docstring along with the function signature.
Purpose of Docstrings:
Self-Documentation: They make your code easier to understand for anyone reading it (including your future self!).
Automated Documentation Tools: Tools like Sphinx can extract docstrings to automatically generate professional-looking API documentation in various formats (HTML, PDF, etc.).
IDE/Editor Support: Integrated Development Environments (IDEs) and text editors (like VS Code, PyCharm) use docstrings to provide helpful pop-up information when you hover over function calls or use auto-completion.
Readability: They provide a quick overview of what a function does without having to read through the entire code implementation.
Docstring Conventions (PEP 257):
One-line docstrings: For very brief functions, a single line might suffice.
Pythondef square(x): """Return the square of x.""" return x * x
Multi-line docstrings: For more complex functions, use a multi-line docstring with the following structure (as shown in the
add_numbers
example):A one-line summary.
A blank line.
More detailed description.
Information about arguments (
Args:
), return values (Returns:
), and any exceptions raised (Raises:
).
Docstring Formats: While not strictly enforced by Python, several popular formats exist for structured docstrings that are easily parsed by documentation generators:
reStructuredText (reST): Used by Sphinx (very common).
NumPy/SciPy style: Popular in scientific computing.
Google style: Another widely used format.
The
add_numbers
example above follows a style similar to Google or NumPy style, clearly outliningArgs
,Returns
, andRaises
.
In summary, docstrings are an essential part of writing clean, maintainable, and well-documented Python code. Always strive to include them for functions, classes, and modules to make your code more accessible and understandable.
0 件のコメント:
コメントを投稿