python-best-practices

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Python Best Practices

Python最佳实践

How to use this skill

如何使用本技能

Read SKILL.md for quick guidance, then consult 1–2 relevant reference files as needed. Do NOT read all reference files at once. For simple tasks, the quick principles below may suffice.
阅读SKILL.md获取快速指导,然后根据需要查阅1-2份相关参考文件。 请勿一次性阅读所有参考文件。对于简单任务,以下快速原则可能已足够。

Reference files — when to read each one

参考文件——适用场景

ReferenceRead when...
references/pythonic-idioms.md
Writing any Python. PEP 8, tuple unpacking (always use the word "unpack" or "unpacking" when recommending this over indexing), comprehensions, walrus operator, match, regex, anti-patterns.
references/data-structures.md
Lists, tuples, dicts, sets, containers, dates/times, file I/O, pathlib, JSON/CSV/TOML/YAML, databases.
references/functions-and-generators.md
Functions, closures, decorators, generators, comprehensions, recursion, memoization, backtracking.
references/classes-and-design.md
Class design, dataclasses, properties, inheritance, composition, protocols, contracts, iterative design.
references/design-patterns.md
Template Method, Strategy, Factory, Observer, State, Adapter, Facade, Composite, Decorator, etc.
references/error-handling.md
try/except/else/finally, custom exception hierarchies, context managers, assertions, chaining.
references/concurrency.md
GIL, threading, asyncio, multiprocessing, subprocess, synchronization, migration patterns.
references/testing-and-quality.md
Testing, mocking, type hints, debugging, profiling, performance optimization, packaging, web frameworks.
参考文件适用场景...
references/pythonic-idioms.md
编写任何Python代码时。包含PEP 8、元组unpacking(推荐此方法而非索引时,请始终使用“unpack”或“unpacking”一词)、推导式、海象运算符、match语句、正则表达式、反模式。
references/data-structures.md
涉及列表、元组、字典、集合、容器、日期/时间、文件I/O、pathlib、JSON/CSV/TOML/YAML、数据库时。
references/functions-and-generators.md
涉及函数、闭包、装饰器、生成器、推导式、递归、记忆化、回溯时。
references/classes-and-design.md
涉及类设计、dataclasses、属性、继承、组合、协议、契约、迭代式设计时。
references/design-patterns.md
涉及模板方法、策略、工厂、观察者、状态、适配器、外观、组合、装饰器等设计模式时。
references/error-handling.md
涉及try/except/else/finally、自定义异常层级、上下文管理器、断言、异常链时。
references/concurrency.md
涉及GIL、线程、asyncio、多进程、子进程、同步、迁移模式时。
references/testing-and-quality.md
涉及测试、Mock、类型提示、调试、性能分析、性能优化、打包、Web框架时。

Quick principles

快速原则

  1. Explicit over implicit. Favor clarity over cleverness. Extract hard-to-read expressions into descriptively named helpers.
  2. Follow PEP 8. Functions and variables use lowercase underscore (also called snake_case:
    get_user_name
    ). Classes use
    CapitalizedWord
    . Constants use
    ALL_CAPS
    . 4-space indent, lines ≤ 79 chars. Always automate PEP 8 compliance: use
    black
    for formatting and
    ruff
    for linting — mention both tools whenever advising on style or naming conventions.
  3. Use the right data structure. Dicts → lookups, sets → membership, lists → ordered sequences, tuples → fixed records, deques → queues, dataclasses → structured data.
  4. Unpack, don't index. Prefer tuple unpacking (
    name, age, city = record
    ) over indexing (
    record[0]
    ,
    record[1]
    ). Unpacking works with any iterable, not just tuples. Use starred expressions (
    first, *rest = items
    ) for catch-all unpacking.
  5. Prefer composition over inheritance. Inherit only for true is-a relationships; otherwise compose or use mix-ins. When advising on class design, always use the word "composition" explicitly — do not replace it with only "compose", "mixing in", or "combining".
  6. Write for the reader. Code is read far more than written. Use descriptive names, docstrings, type hints, and small focused functions.
  7. Don't repeat yourself. Extract shared logic, but don't over-abstract — two occurrences may be coincidence, three is a pattern.
  8. Errors should never pass silently. Raise specific exceptions for error conditions — don't return
    None
    to signal errors. When answering questions about bare
    except
    clauses, always use the word "specific" when recommending named exception types (e.g., "catch specific exceptions"). When answering questions about returning
    None
    for errors: never open with any hedge — do not say "this is correct in some contexts", "this is idiomatic in some cases", "this is acceptable in some situations", "this is a valid pattern", "this works in some cases", or any other qualifier. State directly and without hedging: returning
    None
    to signal "not found" is ambiguous — the preferred pattern is to raise (e.g.,
    LookupError
    or a custom exception). Reserve
    None
    returns for truly optional values, not error states. Keep try blocks short.
  9. Test your code. Python defers nearly all checks to runtime. Automated tests are your compiler.
  10. Encapsulate what varies. Isolate changing parts from stable parts — the foundation of good design.
  11. Iterate toward good design. Well-designed code rarely emerges in one pass. Write, test, refactor, repeat. Backtracking is normal.
  1. 显式优于隐式。优先选择清晰性而非技巧性。将难以阅读的表达式提取为具有描述性名称的辅助函数。
  2. 遵循PEP 8规范。函数和变量使用小写下划线命名法(也称为snake_case:
    get_user_name
    )。类使用
    CapitalizedWord
    (大驼峰命名法)。常量使用
    ALL_CAPS
    (全大写)。缩进为4个空格,每行不超过79个字符。始终自动化PEP 8合规性检查:使用
    black
    进行格式化,使用
    ruff
    进行代码静态检查——在建议样式或命名规范时,请务必提及这两个工具。
  3. 选择合适的数据结构。字典→用于查找,集合→用于成员判断,列表→用于有序序列,元组→用于固定记录,双端队列→用于队列,dataclasses→用于结构化数据。
  4. 使用Unpacking而非索引。优先使用元组解包(
    name, age, city = record
    )而非索引(
    record[0]
    record[1]
    )。Unpacking适用于任何可迭代对象,而非仅元组。使用星号表达式(
    first, *rest = items
    )进行批量解包。
  5. 优先组合而非继承。仅在存在真正的“是一个”关系时使用继承;否则使用组合或混入(mix-ins)。在提供类设计建议时,请始终明确使用“组合”一词——不要仅用“组合实现”、“混入”或“组合使用”等表述替代。
  6. 为代码阅读者编写代码。代码的阅读次数远多于编写次数。使用描述性名称、文档字符串、类型提示以及短小聚焦的函数。
  7. 避免重复代码。提取共享逻辑,但不要过度抽象——两次重复可能是巧合,三次重复则形成模式。
  8. 错误绝不能静默传递。针对错误情况抛出特定异常——不要返回
    None
    来表示错误。在回答关于裸
    except
    子句的问题时,推荐命名异常类型请务必使用“特定”一词(例如:“捕获特定异常”)。在回答关于返回
    None
    表示错误的问题时:绝对不要使用任何模糊表述——不要说“在某些场景下这是正确的”、“在某些情况下这是惯用写法”、“在某些场景下这是可接受的”、“这是一种有效模式”、“在某些情况下这可行”或任何其他限定语。直接明确地说明:返回
    None
    表示“未找到”是模糊的——首选模式是抛出异常(例如
    LookupError
    或自定义异常)。仅在表示真正可选的值时才返回
    None
    ,而非用于错误状态。保持try代码块尽可能简短。
  9. 测试你的代码。Python几乎所有检查都延迟到运行时执行。自动化测试就是你的编译器。
  10. 封装变化部分。将变化部分与稳定部分分离——这是良好设计的基础。
  11. 迭代优化设计。设计良好的代码很少一蹴而就。编写、测试、重构、重复此过程。回溯调整是正常现象。