python-clean-code

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Clean Python: Complete Reference

整洁Python:完整参考指南

Enforces all Clean Code principles from Robert C. Martin's Chapter 17, adapted for Python.
严格遵循Robert C. Martin《代码整洁之道》第17章中的所有原则,并适配Python语言特性。

Comments (C1-C5)

注释规范(C1-C5)

  • C1: No metadata in comments (use Git)
  • C2: Delete obsolete comments immediately
  • C3: No redundant comments
  • C4: Write comments well if you must
  • C5: Never commit commented-out code
  • C1:注释中不要包含元数据(使用Git管理)
  • C2:立即删除过时注释
  • C3:避免冗余注释
  • C4:若必须添加注释,请确保其质量
  • C5:绝对不要提交被注释掉的代码

Environment (E1-E2)

环境规范(E1-E2)

  • E1: One command to build (
    pip install -e ".[dev]"
    )
  • E2: One command to test (
    pytest
    )
  • E1:一键构建(
    pip install -e ".[dev]"
  • E2:一键测试(
    pytest

Functions (F1-F4)

函数规范(F1-F4)

  • F1: Maximum 3 arguments (use dataclasses for more)
  • F2: No output arguments (return values)
  • F3: No flag arguments (split functions)
  • F4: Delete dead functions
  • F1:函数参数最多3个(参数更多时使用dataclasses)
  • F2:不要使用输出参数(改用返回值)
  • F3:不要使用标志参数(拆分函数)
  • F4:删除废弃函数

General (G1-G36)

通用规范(G1-G36)

  • G1: One language per file
  • G2: Implement expected behavior
  • G3: Handle boundary conditions
  • G4: Don't override safeties
  • G5: DRY - no duplication
  • G6: Consistent abstraction levels
  • G7: Base classes don't know children
  • G8: Minimize public interface
  • G9: Delete dead code
  • G10: Variables near usage
  • G11: Be consistent
  • G12: Remove clutter
  • G13: No artificial coupling
  • G14: No feature envy
  • G15: No selector arguments
  • G16: No obscured intent
  • G17: Code where expected
  • G18: Prefer instance methods
  • G19: Use explanatory variables
  • G20: Function names say what they do
  • G21: Understand the algorithm
  • G22: Make dependencies physical
  • G23: Prefer polymorphism to if/else
  • G24: Follow conventions (PEP 8)
  • G25: Named constants, not magic numbers
  • G26: Be precise
  • G27: Structure over convention
  • G28: Encapsulate conditionals
  • G29: Avoid negative conditionals
  • G30: Functions do one thing
  • G31: Make temporal coupling explicit
  • G32: Don't be arbitrary
  • G33: Encapsulate boundary conditions
  • G34: One abstraction level per function
  • G35: Config at high levels
  • G36: Law of Demeter (no train wrecks)
  • G1:单个文件仅使用一种编程语言
  • G2:实现符合预期的行为
  • G3:处理边界条件
  • G4:不要覆盖安全机制
  • G5:DRY原则——避免代码重复
  • G6:保持一致的抽象层级
  • G7:基类不应知晓子类的存在
  • G8:最小化公共接口
  • G9:删除废弃代码
  • G10:变量定义应靠近其使用位置
  • G11:保持一致性
  • G12:移除冗余代码
  • G13:避免人为耦合
  • G14:避免特性羡慕(Feature Envy)
  • G15:不要使用选择器参数
  • G16:不要隐藏代码意图
  • G17:代码放置在预期的位置
  • G18:优先使用实例方法
  • G19:使用具有解释性的变量
  • G20:函数名称应准确描述其功能
  • G21:理解所使用的算法
  • G22:明确依赖关系
  • G23:优先使用多态而非if/else语句
  • G24:遵循编码规范(PEP 8)
  • G25:使用命名常量,而非魔法数字
  • G26:代码要精确
  • G27:优先使用结构化设计而非约定
  • G28:封装条件判断
  • G29:避免使用否定条件
  • G30:函数只做一件事
  • G31:明确时序耦合
  • G32:避免随意的代码设计
  • G33:封装边界条件
  • G34:单个函数保持单一抽象层级
  • G35:在高层级处理配置
  • G36:遵循迪米特法则(避免链式调用)

Python-Specific (P1-P3)

Python特定规范(P1-P3)

These adapt the Java-specific rules (J1-J3) to Python conventions:
  • P1: No wildcard imports (
    from x import *
    ) — opposite of Java, per PEP 8
  • P2: Use Enums, not magic constants — same principle as J3
  • P3: Type hints on public interfaces — Python's equivalent of Java's static typing
这些规范是将Java特定规则(J1-J3)适配为Python约定:
  • P1:不要使用通配符导入(
    from x import *
    )——与Java相反,符合PEP 8规范
  • P2:使用Enums,而非魔法常量——与J3原则一致
  • P3:公共接口添加类型提示——Python版本的Java静态类型检查

Names (N1-N7)

命名规范(N1-N7)

  • N1: Choose descriptive names
  • N2: Right abstraction level
  • N3: Use standard nomenclature
  • N4: Unambiguous names
  • N5: Name length matches scope
  • N6: No encodings
  • N7: Names describe side effects
  • N1:选择具有描述性的名称
  • N2:名称要匹配正确的抽象层级
  • N3:使用标准命名法
  • N4:名称要明确无歧义
  • N5:名称长度要与作用域匹配
  • N6:不要在名称中包含编码信息
  • N7:名称要能描述副作用

Tests (T1-T9)

测试规范(T1-T9)

  • T1: Test everything that could break
  • T2: Use coverage tools
  • T3: Don't skip trivial tests
  • T4: Ignored test = ambiguity question
  • T5: Test boundary conditions
  • T6: Exhaustively test near bugs
  • T7: Look for patterns in failures
  • T8: Check coverage when debugging
  • T9: Tests must be fast (< 100ms each)
  • T1:对所有可能出错的部分进行测试
  • T2:使用覆盖率工具
  • T3:不要跳过简单测试
  • T4:被忽略的测试意味着存在歧义问题
  • T5:测试边界条件
  • T6:对bug附近的代码进行全面测试
  • T7:从失败案例中寻找规律
  • T8:调试时检查代码覆盖率
  • T9:测试必须快速(每个测试耗时<100ms)

Quick Reference Table

快速参考表

CategoryRuleOne-Liner
CommentsC1No metadata (use Git)
C3No redundant comments
C5No commented-out code
FunctionsF1Max 3 arguments
F3No flag arguments
F4Delete dead functions
GeneralG5DRY—no duplication
G9Delete dead code
G16No obscured intent
G23Polymorphism over if/else
G25Named constants, not magic numbers
G30Functions do one thing
G36Law of Demeter (one dot)
NamesN1Descriptive names
N5Name length matches scope
TestsT5Test boundary conditions
T9Tests must be fast
分类规则一句话总结
注释规范C1不要包含元数据(使用Git管理)
C3避免冗余注释
C5不要提交被注释掉的代码
函数规范F1最多3个参数
F3不要使用标志参数
F4删除废弃函数
通用规范G5DRY——避免重复
G9删除废弃代码
G16不要隐藏代码意图
G23优先使用多态而非if/else
G25使用命名常量,而非魔法数字
G30函数只做一件事
G36迪米特法则(最多一个点)
命名规范N1使用描述性名称
N5名称长度与作用域匹配
测试规范T5测试边界条件
T9测试必须快速

Anti-Patterns (Don't → Do)

反模式(不要做 → 应该做)

❌ Don't✅ Do
Comment every lineDelete obvious comments
Helper for one-linerInline the code
from x import *
Explicit imports
Magic number
86400
SECONDS_PER_DAY = 86400
process(data, True)
process_verbose(data)
Deep nestingGuard clauses, early returns
obj.a.b.c.value
obj.get_value()
100+ line functionSplit by responsibility
❌ 不要做✅ 应该做
每行代码都加注释删除显而易见的注释
为单行代码写辅助函数直接内联代码
from x import *
使用显式导入
魔法数字
86400
SECONDS_PER_DAY = 86400
process(data, True)
process_verbose(data)
深层嵌套使用卫语句、提前返回
obj.a.b.c.value
obj.get_value()
超过100行的函数按职责拆分函数

AI Behavior

AI行为规范

When reviewing code, identify violations by rule number (e.g., "G5 violation: duplicated logic"). When fixing or editing code, report what was fixed (e.g., "Fixed: extracted magic number to
SECONDS_PER_DAY
(G25)").
审查代码时,需按规则编号指出违规问题(例如:"G5违规:存在重复逻辑")。 修复或编辑代码时,需说明修复内容(例如:"已修复:将魔法数字提取为
SECONDS_PER_DAY
(G25)")。