code-quality

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Python Code Quality

Python代码质量

High-value Python code-quality anti-patterns to check during review or self-review. This skill is review-focused: it covers correctness and readability defects that a reviewer (or a linter) should flag, separate from testing mechanics (
pytest
) and whole-codebase health scoring (
code-quality-scoring
).
Source note: These anti-patterns are derived from CAST Highlight's Python code quality indicators (https://doc.casthighlight.com/), which reference PEP 8 and the Python data model as primary sources. Where a rule mirrors PEP 8, the PEP is the authoritative source. All examples are original.
代码审查或自我审查中需重点关注的高价值Python代码质量反模式。本技能聚焦于审查环节:涵盖审查人员(或代码检查工具)应标记的正确性与可读性缺陷,与测试机制(
pytest
)和全代码库健康评分(
code-quality-scoring
)相区分。
来源说明: 这些反模式源自CAST Highlight的Python代码质量指标(https://doc.casthighlight.com/),其主要参考**PEP 8**和Python数据模型。若某规则与PEP 8一致,则以PEP 8为权威来源。所有示例均为原创。

When to Use This Skill

适用场景

Use it when the task is "is this Python code clean and correct?" — for example:
  • Reviewing a pull request and checking for the defects below.
  • Self-reviewing before opening a PR.
  • Configuring
    ruff
    /
    pylint
    /
    mypy
    rules so CI catches these automatically.
  • Writing or updating a team's Python code-quality guidance.
Do not use it for testing mechanics (use the
pytest
skill) or for scoring a whole codebase's health and technical debt (use the
code-quality-scoring
skill).
当你需要判断「这段Python代码是否简洁正确?」时使用本技能,例如:
  • 审查拉取请求(pull request),检查以下缺陷。
  • 提交PR前进行自我审查。
  • 配置
    ruff
    /
    pylint
    /
    mypy
    规则,让CI自动检测这些问题。
  • 编写或更新团队的Python代码质量指南。
请勿将其用于测试机制(请使用
pytest
技能),或用于评估全代码库的健康状况与技术债务(请使用
code-quality-scoring
技能)。

Core Anti-Patterns (Summary)

核心反模式(摘要)

Six highest-value Python anti-patterns. Each has a non-compliant/compliant example and a "how to test" note in the reference doc:
  • Custom exceptions must derive from
    Exception
    — a class meant to be raised that inherits from
    object
    fails at runtime and breaks every
    except
    clause.
  • Compare singletons with
    is
    , not
    ==
    — use
    is
    /
    is not
    for
    None
    /
    True
    /
    False
    (PEP 8); use
    is
    only for singletons, never for value comparison.
  • Avoid bare / overly broad
    except
    — catch the narrowest type you can handle; a generic
    except Exception
    only as a last-position fallback that logs or re-raises.
  • Avoid wildcard imports (
    from x import *
    ) — they hide dependencies, risk silent name collisions, and defeat static analysis.
  • Replace magic numbers with named constants — promote non-obvious literals to documented, named constants.
  • Remove unused local variables — a dead assignment misleads readers and can hide a bug where a value was meant to be used.
六大高价值Python反模式。每个反模式在参考文档中均包含非合规/合规示例以及「测试方法」说明:
  • 自定义异常必须继承自
    Exception
    —— 若一个用于抛出的类继承自
    object
    ,会在运行时失败,并破坏所有
    except
    子句。
  • 使用
    is
    而非
    ==
    比较单例
    —— 对
    None
    /
    True
    /
    False
    使用
    is
    /
    is not
    (符合PEP 8);仅对单例使用
    is
    ,绝不能用于值比较。
  • 避免裸
    except
    或过于宽泛的
    except
    —— 捕获你能处理的最窄类型;仅将通用的
    except Exception
    作为最后一步的回退方案,用于日志记录或重新抛出异常。
  • 避免通配符导入
    from x import *
    )—— 它们会隐藏依赖关系,存在静默命名冲突的风险,且会失效静态分析。
  • 用命名常量替换魔术数字 —— 将非直观的字面量提升为带文档说明的命名常量。
  • 移除未使用的局部变量 —— 无效的赋值会误导读者,还可能隐藏本应使用该值的bug。

Best Practices

最佳实践

  • Gate these in CI. Most are enforceable cheaply with
    ruff
    (F403/F405 wildcard, F841 unused locals,
    E711
    /
    E712
    singleton comparison),
    pylint
    , and
    mypy
    . Put the lint step in CI so review effort focuses on judgment, not mechanics.
  • Prefer specific exception handlers. Order handlers narrowest-first; reserve a generic
    except Exception
    for a logging/re-raising last resort.
  • Name intent, not values. A constant's name documents why a threshold exists; a bare literal documents nothing.
  • 在CI中设置检查关卡。大多数反模式可通过
    ruff
    (F403/F405通配符导入、F841未使用局部变量、
    E711
    /
    E712
    单例比较)、
    pylint
    mypy
    低成本强制执行。将代码检查步骤加入CI,让审查工作聚焦于判断而非机械性检查。
  • 优先使用特定异常处理器。按范围从窄到宽的顺序排列处理器;仅将通用的
    except Exception
    作为日志记录/重新抛出异常的最后手段。
  • 命名体现意图,而非值。常量的名称应说明阈值存在的原因;而裸字面量则无法提供任何信息。

Anti-Patterns (What to Avoid)

需避免的反模式

  • Inheriting custom exceptions from
    object
    or directly from
    BaseException
    .
  • == None
    ,
    == True
    , or
    is "some literal"
    .
  • Bare
    except:
    or
    except BaseException:
    that swallows control-flow signals.
  • from module import *
    outside a curated
    __init__.py
    with explicit
    __all__
    .
  • Unexplained numeric literals in business logic.
  • Assigned-but-never-read locals left behind by a stale refactor.
  • 自定义异常继承自
    object
    或直接继承自
    BaseException
  • 使用
    == None
    == True
    is "some literal"
  • 使用裸
    except:
    except BaseException:
    吞噬控制流信号。
  • 在未经过精心设计且未显式定义
    __all__
    __init__.py
    中使用
    from module import *
  • 业务逻辑中出现未加解释的数值字面量。
  • 因过时重构留下的已赋值但从未读取的局部变量。

Navigation

导航

  • quality-antipatterns.md: Full non-compliant vs compliant examples and a "how to test" note for each of the six anti-patterns.
  • quality-antipatterns.md:包含六大反模式的完整非合规与合规示例,以及每个反模式的「测试方法」说明。

Related Skills

相关技能

  • pytest (
    toolchains/python/testing/pytest
    ): testing mechanics — fixtures, parametrization, mocking. Several anti-patterns here (broad
    except
    , malformed exception classes) directly cause flaky tests.
  • code-review-standards (
    universal/process/code-review-standards
    ): the project-wide, severity-tagged review checklist that incorporates equivalents of these.
  • code-quality-scoring (
    universal/quality/code-quality-scoring
    ): whole-codebase health and technical-debt scoring, rather than individual findings.
  • pytest
    toolchains/python/testing/pytest
    ):测试机制 —— 夹具、参数化、模拟。本技能中的部分反模式(宽泛的
    except
    、格式错误的异常类)会直接导致测试不稳定。
  • code-review-standards
    universal/process/code-review-standards
    ):项目级、带严重程度标记的审查清单,其中包含与本技能等效的内容。
  • code-quality-scoring
    universal/quality/code-quality-scoring
    ):全代码库健康状况与技术债务评分,而非单个问题排查。