Skip to content

Python 简明代码规范

AI RulesQuick Reference

本规范用于生成标准、可读、无明显缺陷的 Python 代码。 进阶优化(如性能调优、设计模式)不在此规范范围内,按需使用即可。


一、🏷️ 命名规范 (Naming)

类型风格示例
变量/函数snake_caseuser_id, get_user
常量SCREAMING_SNAKE_CASEMAX_RETRY
PascalCaseUserProfile
布尔变量is_/has_/can_ 前缀is_active

二、📝 类型注解 (Type Hints)

  • 所有函数必须有类型注解
  • 使用 str | None 而非 Optional[str](Python 3.10+)
  • 使用 list[int] 而非 List[int](Python 3.9+)
python
def get_user(user_id: int) -> dict | None:
    ...

三、📋 文档规范 (Documentation)

  • 公共函数必须有 Docstring(Google Style)
  • 注释解释 "为什么",不要复述代码
python
def calculate_tax(amount: float) -> float:
    """计算税额。
    
    Args:
        amount: 金额,必须为正数。
        
    Returns:
        计算后的税额。
    """
    # 使用固定税率是因为本系统只服务单一地区
    return amount * TAX_RATE

四、🔢 数值规范 (Numbers)

  • 禁止魔术数字,用常量替代
python
# ❌ Bad
if retry_count > 3:
    ...

# ✅ Good
MAX_RETRY = 3
if retry_count > MAX_RETRY:
    ...

五、📜 字符串规范 (Strings)

  • 使用 f-string 格式化
  • 文件操作必须指定 encoding='utf-8'
  • SQL 用参数化查询,禁止拼接
python
# ✅ f-string
message = f"Hello, {name}!"

# ✅ 文件编码
with open('data.txt', 'r', encoding='utf-8') as f:
    ...

# ✅ 参数化 SQL
cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))

六、🎨 代码风格 (Style)

  • 复杂条件提取为布尔变量
  • 用空行分隔逻辑块
python
# ✅ 提取复杂条件
is_eligible = user.age >= 18 and user.has_verified_email
if is_eligible:
    grant_access()

七、🚫 禁止事项 (Forbidden)

禁止原因
僵尸代码(被注释的无用代码)使用 Git 历史恢复代码
魔术数字使用常量提高可读性
SQL 字符串拼接防止注入攻击

← 返回 Python 深度研究