文档与注释
良好的文档和注释是代码可维护性的基础。Python 2.7 通过文档字符串(docstring)、注释、类型提示(有限支持)和代码风格规范,帮助开发者写出清晰易懂的代码。
文档字符串 Docstring
模块、类、函数的文档用三引号字符串写在定义的第一行:
def calculate_area(length, width):
"""Calculate the area of a rectangle.
Args:
length (float): The length of the rectangle.
width (float): The width of the rectangle.
Returns:
float: The area (length * width).
Raises:
ValueError: If length or width is negative.
Examples:
>>> calculate_area(5, 3)
15.0
>>> calculate_area(0, 10)
0.0
"""
if length < 0 or width < 0:
raise ValueError("Dimensions must be non-negative")
return length * width
访问文档字符串:
print calculate_area.__doc__
help(calculate_area) # 更友好的格式化输出
模块级文档:
"""String utilities for text processing.
This module provides functions for common string operations
including formatting, validation, and transformation.
Usage:
import string_utils
result = string_utils.capitalize_words("hello world")
"""
import re
def capitalize_words(text):
"""Capitalize the first letter of each word."""
return re.sub(r'\b\w', lambda m: m.group().upper(), text)
注释
注释解释"为什么",代码解释"做什么":
# 好的注释:解释意图和原因
# 使用二分查找因为数据已排序且量大
index = binary_search(sorted_data, target)
# 坏的注释:重复代码
# 将 x 加 1
x = x + 1
# 好的注释:标记待办
# TODO: 处理边界情况 n=0
# FIXME: 当前实现 O(n^2),需要优化
# NOTE: 这个算法假设输入已排序
# HACK: 临时方案,需要重构
行内注释:
x = x + 1 # 补偿边界偏移
行内注释应简洁,放在代码右侧,与代码之间至少两个空格。
PEP 257 文档字符串规范
PEP 257 定义了文档字符串的编写规范:
- 所有公共模块、函数、类、方法都需要 docstring
- 非公共方法也需要 docstring,说明作用
- 第一行是简短摘要,以句号结尾
- 第二行空行
- 后续行详细说明
class BankAccount(object):
"""A simple bank account implementation.
Supports deposits, withdrawals, and balance inquiries.
Does not handle interest or fees.
"""
def __init__(self, initial_balance=0):
"""Initialize account with optional starting balance.
Args:
initial_balance (int, optional): Starting balance. Defaults to 0.
"""
self.balance = initial_balance
def deposit(self, amount):
"""Add funds to the account.
Args:
amount (int): Amount to deposit. Must be positive.
Returns:
int: New balance after deposit.
"""
self.balance += amount
return self.balance
生成文档
pydoc:Python 内置文档生成工具
python -m pydoc mymodule # 查看模块文档
python -m pydoc -p 8080 # 启动 HTTP 文档服务器
Sphinx:专业的文档生成工具(需安装)
pip install sphinx
sphinx-quickstart docs/ # 初始化文档项目
Sphinx 支持 reStructuredText 格式,可以从 docstring 自动生成 API 文档。
代码可读性
命名规范:
| 类型 | 规范 | 示例 |
|---|---|---|
| 模块 | 小写,下划线 | my_module.py |
| 包 | 小写,无下划线 | mypackage |
| 类 | 大写驼峰 | BankAccount |
| 函数/方法 | 小写,下划线 | calculate_area |
| 常量 | 大写,下划线 | MAX_SIZE |
| 私有 | 下划线前缀 | _internal_func |
函数长度:
一个函数应该只做一件事。如果函数超过 20 行,考虑拆分:
# 不好的:一个函数做太多事
def process_user_data(data):
# 验证
if not data:
return None
# 清洗
cleaned = data.strip().lower()
# 转换
converted = int(cleaned)
# 存储
save_to_db(converted)
# 通知
send_notification(converted)
return converted
# 好的:拆分为小函数
def validate_data(data):
return data.strip().lower() if data else None
def parse_user_id(data):
return int(data)
def process_user_data(data):
cleaned = validate_data(data)
if not cleaned:
return None
user_id = parse_user_id(cleaned)
save_to_db(user_id)
send_notification(user_id)
return user_id
实际应用
项目 README:
# MyProject
A brief description of what this project does.
## Installation
```bash
pip install -r requirements.txt
Usage
from myproject import Client
client = Client(api_key="your-key")
result = client.query("example")
API Reference
See docs/api.md for detailed documentation.
**CHANGELOG**:
```markdown
# Changelog
## 1.1.0 (2024-01-15)
- Added support for batch operations
- Fixed memory leak in long-running processes
## 1.0.0 (2024-01-01)
- Initial release
文档驱动开发
先写文档,再写代码:
- 定义函数签名和 docstring
- 写测试验证 docstring 中的示例
- 实现函数使测试通过
def parse_date(date_string):
"""Parse ISO format date string.
Args:
date_string (str): Date in 'YYYY-MM-DD' format.
Returns:
datetime.date: Parsed date object.
Raises:
ValueError: If format is invalid.
Examples:
>>> parse_date('2024-01-15')
datetime.date(2024, 1, 15)
>>> parse_date('invalid')
Traceback (most recent call last):
...
ValueError: Invalid date format
"""
# 实现...
pass
文档中的 >>> 示例可以用 doctest 模块自动测试:
python -m doctest mymodule.py -v