Python 代码规范权威指南

基于 PEP 官方规范和权威机构最佳实践的完整代码风格指南,助力编写高质量、可维护的 Python 代码

11 核心章节
50+ 代码示例
3 官方 PEP

概述

本指南整合了 Python 官方 PEP 规范和 Google 等权威机构的编码标准,提供全面的代码风格指导。遵循这些规范将帮助您编写更清晰、一致和可维护的代码。

为什么需要代码规范?

  • 提高代码可读性和一致性
  • 便于团队协作和代码审查
  • 减少维护成本和错误率
  • 支持自动化工具和 IDE 功能

PEP 8 代码风格指南

PEP 8 是 Python 官方代码风格指南,定义了编写 Python 代码的标准约定。

代码布局

缩进

使用 4 个空格进行缩进,避免使用制表符。

推荐做法

正确的缩进示例
def long_function_name(
        var_one, var_two, var_three,
        var_four):
    print(var_one)

行长度

每行最多 79 个字符,文档字符串或注释最多 72 个字符。

注意

许多现代项目使用 88 或 120 个字符作为行长度限制,这是 PEP 8 最常见的偏差。

正确的长行处理
# 使用括号换行
foo_bar(self, width, height, color='black', design=None, 
        x='foo', emphasis=None, highlight=0)

# 字符串连接
x = ('This will build a very long long '
     'long long long long long long string')

空行

  • 顶级函数和类定义前后用两个空行分隔
  • 类内方法定义用一个空行分隔
  • 函数内用空行分隔逻辑段落
空行使用示例
class MyClass:
    """一个示例类。"""

    def __init__(self):
        """初始化方法。"""
        self.value = 0

    def method_one(self):
        """第一个方法。"""
        return self.value

    def method_two(self):
        """第二个方法。"""
        return self.value * 2


def standalone_function():
    """独立函数。"""
    pass

PEP 257 文档字符串规范

PEP 257 定义了 Python 文档字符串(docstring)的编写约定。

基本规则

  • 使用三重双引号(""")
  • 紧跟在定义语句后的第一行
  • 单行 docstring 写在一行内
  • 多行 docstring 包含摘要行、空行和详细描述

单行文档字符串

单行 docstring 示例
def square(x):
    """返回 x 的平方。"""
    return x * x

多行文档字符串

多行 docstring 示例
def complex_function(arg1, arg2, **kwargs):
    """执行复杂的计算操作。

    这个函数接受两个必需参数和可选的关键字参数,
    执行复杂的数学计算并返回结果。

    Args:
        arg1 (int): 第一个操作数
        arg2 (float): 第二个操作数
        **kwargs: 可选的配置参数

    Returns:
        float: 计算结果

    Raises:
        ValueError: 当参数无效时抛出
        TypeError: 当参数类型错误时抛出

    Example:
        >>> result = complex_function(10, 3.14, precision=2)
        >>> print(result)
        31.4
    """
    if not isinstance(arg1, int):
        raise TypeError("arg1 must be an integer")
    return arg1 * arg2

PEP 484 类型注解规范

PEP 484 引入了类型提示机制,提高代码可读性和工具支持。

基础类型注解

基础类型注解示例
def greet(name: str) -> str:
    """问候函数。
    
    Args:
        name: 被问候者的姓名
        
    Returns:
        问候语
    """
    return f"Hello, {name}!"

# 变量注解
age: int = 25
price: float = 99.99
is_active: bool = True

容器类型

容器类型注解示例
from typing import List, Dict, Tuple, Set, Optional, Union

def process_items(items: List[str]) -> Dict[str, int]:
    """处理项目列表。
    
    Args:
        items: 字符串列表
        
    Returns:
        字符串到整数的映射
    """
    return {item: len(item) for item in items}

# 复杂类型注解
coordinates: Tuple[float, float] = (10.5, 20.3)
user_ids: Set[int] = {1, 2, 3, 4}
config: Dict[str, Union[str, int, bool]] = {
    "debug": True,
    "port": 8080,
    "host": "localhost"
}

Google Python 风格指南

Google Python 风格指南在 PEP 8 基础上提供了更详细的规范和最佳实践。

导入规范

Google 导入风格示例
# 标准库导入
import os
import sys
from typing import List, Dict, Optional

# 第三方库导入
import numpy as np
import pandas as pd
import requests

# 本地应用导入
from myproject import config
from myproject.utils import helper_function
from myproject.models import User

异常处理

推荐做法

正确的异常处理
try:
    result = risky_operation()
except SpecificError as e:
    logger.error(f"Specific error occurred: {e}")
    raise
except (ValueError, TypeError) as e:
    logger.warning(f"Input error: {e}")
    return default_value
finally:
    cleanup_resources()

避免的做法

不推荐的异常处理
# 避免捕获所有异常
try:
    risky_operation()
except:  # 太宽泛
    pass  # 忽略错误

命名规范

一致的命名约定是编写可读代码的关键。

命名风格

命名约定示例
# 模块和包名:小写,可使用下划线
import user_manager
from data_processing import csv_parser

# 类名:大驼峰命名法(CapWords)
class UserManager:
    pass

class HTTPConnectionPool:
    pass

# 函数和方法名:小写,使用下划线分隔
def calculate_total():
    pass

def get_user_by_id():
    pass

# 变量名:小写,使用下划线分隔
user_count = 10
max_retry_attempts = 3

# 常量:全部大写,使用下划线分隔
MAX_CONNECTIONS = 100
DEFAULT_TIMEOUT = 30
API_BASE_URL = "https://api.example.com"

注释规范

好的注释解释代码的目的和上下文,而不是显而易见的操作。

块注释

块注释示例
# 计算复杂度为 O(n log n) 的排序算法
# 适用于大型数据集,但对于小数据集可能不如简单排序快
def merge_sort(arr):
    if len(arr) <= 1:
        return arr
    
    # 分割数组为两半
    mid = len(arr) // 2
    left = merge_sort(arr[:mid])
    right = merge_sort(arr[mid:])
    
    # 合并已排序的两半
    return merge(left, right)

代码格式化

一致的代码格式提高了可读性和维护性。

空格使用

推荐的空格使用

正确的空格使用
# 二元运算符两侧加空格
result = a + b * c
is_valid = x > 0 and y < 10

# 函数调用,逗号后加空格
func(arg1, arg2, arg3)

# 列表、字典、元组
items = [1, 2, 3, 4]
config = {'debug': True, 'port': 8080}
point = (10, 20)

# 切片操作
data[start:end]
data[start:end:step]

# 关键字参数
function(normal_arg, keyword_arg=value)

最佳实践

这些实践将帮助您编写更高质量的 Python 代码。

SOLID 原则在函数设计中的应用

  • 单一职责:每个函数只做一件事
  • 开闭原则:对扩展开放,对修改封闭
  • 接口隔离:不要强迫依赖不需要的接口
优秀的函数设计
def validate_email(email: str) -> bool:
    """验证邮箱格式。
    
    Args:
        email: 待验证的邮箱地址
        
    Returns:
        True 如果邮箱格式有效,False 否则
    """
    import re
    pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    return bool(re.match(pattern, email))

def send_notification(
    recipient: str,
    subject: str,
    message: str,
    notification_type: str = 'email'
) -> bool:
    """发送通知。
    
    Args:
        recipient: 接收者
        subject: 主题
        message: 消息内容
        notification_type: 通知类型(email, sms, push)
        
    Returns:
        True 如果发送成功,False 否则
        
    Raises:
        ValueError: 当通知类型不支持时
    """
    if notification_type not in ['email', 'sms', 'push']:
        raise ValueError(f"Unsupported notification type: {notification_type}")
    
    if notification_type == 'email' and not validate_email(recipient):
        return False
    
    # 发送逻辑
    return True

自动化工具

使用自动化工具可以确保代码风格的一致性并减少手动检查的负担。

Black - 严格的代码格式化器

Black 是一个"无妥协"的代码格式化器,自动处理大部分格式问题。

Black 配置示例
# pyproject.toml
[tool.black]
line-length = 88
target-version = ['py38']
include = '\.pyi?$'
extend-exclude = '''
/(
  # directories
  \.eggs
  | \.git
  | \.hg
  | \.mypy_cache
  | \.tox
  | \.venv
  | build
  | dist
)/
'''

推荐工具链

  • Black: 代码格式化
  • Ruff: 快速 linting 和自动修复
  • mypy: 静态类型检查
  • pre-commit: Git 预提交钩子
  • pytest: 测试框架
  • coverage: 代码覆盖率

参考资料

以下是官方和权威的 Python 代码规范文档链接。

文档更新信息

本文档基于 2025年1月的最新官方规范编写,涵盖了 Python 3.8+ 的特性和最佳实践。建议定期查看官方 PEP 文档获取最新更新。