mcpField
P
python3-add-feature

python3-add-feature

github.com/jamie-bitflight开发37 次安装
代码仓库

关于 python3-add-feature

用于指导 Python 功能开发的工作流技能,涵盖项目探索、规划、测试驱动实现和验证,适合在现有 Python 代码库中添加功能的开发者。

主要功能

  1. 01探索项目结构与现有模式
  2. 02编写功能规格并确定优先级
  3. 03指导测试驱动实现
  4. 04检查 lint、类型与测试
  5. 05核对集成和文档事项

适用场景

  1. 01规划现有 Python 包中的功能
  2. 02在实现新行为前编写测试
  3. 03按项目质量规则检查代码变更

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/jamie-bitflight/claude_skills --skill python3-add-feature

安装后在 Claude Code 中输入/python3-add-feature确认已加载。

详细介绍

<feature_description>$ARGUMENTS</feature_description>

Python 功能添加工作流

模型通过发现、规划、实现和验证阶段指导功能开发。

参数

<feature_description/>

说明

  1. 理解参数中的功能请求
  2. 发现项目上下文(结构、模式、现有代码)
  3. 规划实现(要创建或修改的文件、依赖项)
  4. 遵循 TDD 编写实现和测试
  5. 验证质量(lint、类型、覆盖率)

阶段 1:发现

收集项目上下文
CHECK:
- [ ] pyproject.toml exists and has project configuration
- [ ] src/ or packages/ directory structure
- [ ] tests/ directory with existing test patterns
- [ ] Linting and type-check configuration (ruff; ty and/or mypy per project — see `standards-for-python-development`)
- [ ] Existing patterns for similar features
确定集成点

确定此功能适合的位置:

  • 哪个模块或包负责此功能?
  • 哪些现有类或函数会与之交互?
  • 需要创建哪些新文件?

阶段 2:规划

功能规格

创建清晰的规格:

## Feature: [Name]

**Purpose**: [One sentence describing what this enables]

**User Story**: As a [user type], I want [capability] so that [benefit].

**Acceptance Criteria**:
- [ ] Criterion 1
- [ ] Criterion 2
- [ ] Criterion 3

**Files to Create/Modify**:
- `src/module/new_feature.py` - Main implementation
- `tests/test_new_feature.py` - Test suite
- `src/module/__init__.py` - Export new functionality

**Dependencies**:
- Internal: [existing modules to import]
- External: [new packages if any]
MoSCoW 优先级排序

<moscow_framework>

使用 MoSCoW 对所有需求进行分类:

优先级含义标准
P0(必须有)v1 版本不可妥协的要求缺少此功能,功能就无法正常运行
P1(应该有)重要的、已承诺的后续功能价值高,但没有它 v1 仍可正常运行
P2(可以有)时间允许时值得实现锦上添花的增强功能
暂不实现明确推迟不在此版本范围内

纪律检查:如果所有内容都是 P0,就没有任何内容是真正的 P0。请重新评估。

示例:

### Requirements by Priority

**P0 (Must Have)**:
- [ ] Parse CSV input with header detection
- [ ] Output formatted report to stdout
- [ ] Handle malformed rows with error message

**P1 (Should Have)**:
- [ ] Support custom delimiter (--delimiter)
- [ ] Progress indicator for large files

**P2 (Could Have)**:
- [ ] JSON output format option
- [ ] Column filtering

**Won't Have (This Release)**:
- Excel format support (separate feature)
- Database export (requires new dependency)

</moscow_framework>

验收标准格式

<acceptance_criteria_patterns>

测试型验收标准请使用以下格式之一:

格式 1:Given/When/Then(BDD)

Given [precondition]
When [user action]
Then [expected outcome]

示例:

Given a CSV file with 1000 rows
When the user runs `parse report.csv`
Then the output shows all rows within 2 seconds
And no memory warnings are logged

格式 2:包含具体要求的清单

- [ ] Command `parse --help` shows usage with examples
- [ ] Empty file input returns exit code 1 with message "Empty file"
- [ ] Unicode characters in data are preserved in output
- [ ] Ctrl+C during processing exits cleanly (no stack trace)

应避免的反模式:

反模式问题更好的写法
“应该很快”无法衡量“处理 10K 行数据的耗时小于 2 秒”
“妥善处理错误”含糊不清“输入无效时返回退出码 1,并显示描述性消息”
“用户友好的输出”主观“输出使用带表头的 Rich 表格格式”

</acceptance_criteria_patterns>

先设计接口

在实现之前定义公共 API:

# Define function signatures and docstrings
def new_feature(input_data: InputType, *, option: str = "default") -> ResultType:
    """Process input data with new feature capability.

    Args:
        input_data: The data to process
        option: Configuration option

    Returns:
        Processed result

    Raises:
        ValidationError: If input_data is invalid
    """
    ...

阶段 3:测试驱动实现

先编写测试
import pytest
from pytest_mock import MockerFixture


class TestNewFeature:
    """Tests for new_feature functionality."""

    def test_basic_operation(self) -> None:
        """Test basic feature operation with valid input."""
        # Arrange
        input_data = create_valid_input()

        # Act
        result = new_feature(input_data)

        # Assert
        assert result.status == "success"

    def test_handles_invalid_input(self) -> None:
        """Test feature raises error for invalid input."""
        with pytest.raises(ValidationError, match="Invalid input"):
            new_feature(invalid_input)

    def test_option_affects_behavior(self) -> None:
        """Test that option parameter changes processing."""
        result_default = new_feature(data, option="default")
        result_custom = new_feature(data, option="custom")

        assert result_default != result_custom
实现代码以通过测试
  1. 运行测试——它们应该失败(红)
  2. 编写最精简的代码使测试通过(绿)
  3. 重构以提升质量(重构)
  4. 针对每个测试用例重复以上步骤
实现检查清单
- [ ] All functions have complete type hints
- [ ] Docstrings follow Google style
- [ ] Error handling uses specific exceptions
- [ ] No hardcoded values (use constants or config)
- [ ] Follows existing project patterns

阶段 4:集成

更新模块导出
# src/module/__init__.py
from .new_feature import new_feature, ResultType

__all__ = [
    "new_feature",
    "ResultType",
    # ... existing exports
]
添加到 CLI(如适用)
@app.command()
def feature_command(input_file: Annotated[Path, typer.Argument(help="Input file")]) -> None:
    """Run new feature on input file."""
    result = new_feature(load_data(input_file))
    console.print(f"Result: {result}")

阶段 5:验证

运行质量检查
# Linting
uv run ruff check src/ tests/
uv run ruff format --check src/ tests/

# Type checking — match hooks/CI (ty vs mypy); do not use mypy only because [tool.mypy] exists
uv run ty check src/ tests/
# If hooks/CI run mypy:
# uv run mypy src/ tests/

# Tests with coverage
uv run pytest tests/ --cov=src --cov-report=term-missing
覆盖率策略

覆盖率是行为已得到测试的证据,而不是需要达成的百分比目标。

  • 测试更改涉及的行为、公共约定、边界、错误路径,以及与更改相关且已复现的回归问题。
  • 如果单元测试无法验证面向用户的约定,请添加集成测试或行为测试。
  • 检查更改中未覆盖的分支,并判断它们是否构成实质风险。
  • 遵循仓库现有的覆盖率门槛;如果项目没有门槛,不要自行设置任意百分比。
  • 不要仅为提高行覆盖率而添加价值较低的测试。
成功指标

<success_metrics_framework>

在实现前定义可衡量的成功标准:

先行指标(可在数天至数周内观察):

指标目标衡量方式
测试通过率100%pytest --tb=short
类型覆盖率100%ty check 或项目的 mypy 命令
行为变更覆盖相关契约和风险路径定向测试 + 覆盖率检查
命令启动时间<500mstime uv run <cmd> --help

滞后指标(可在数周至数月内观察):

指标目标衡量方式
用户采用率N 位用户/周使用日志或反馈
错误率<1% 的调用错误日志
支持工单较基线有所减少问题跟踪器

对于 CLI 功能:

# Performance baseline
hyperfine 'uv run <command> <args>' --warmup 3

# Memory usage
/usr/bin/time -v uv run <command> <args> 2>&1 | grep "Maximum resident"

评估窗口:指定何时审查指标(例如,“合并后 1 周”、“100 次调用后”)。

</success_metrics_framework>

文档

更新相关文档:

  • 如果是面向用户的功能,更新 README.md
  • 如果涉及公共接口,更新 API 文档
  • 在 CHANGELOG.md 中添加功能说明

工作流示例

请求:“为报告模块添加 CSV 导出功能”

调研
Project structure:
- src/reports/generator.py - existing report generation
- src/reports/formats/ - existing format handlers
- tests/reports/ - existing report tests

Pattern: Format handlers inherit from BaseFormatter
规划
## Feature: CSV Export

**Purpose**: Export reports in CSV format

**Files**:
- `src/reports/formats/csv_formatter.py` - CSV implementation
- `tests/reports/formats/test_csv_formatter.py` - Tests

**Interface**:
class CsvFormatter(BaseFormatter):
    def format(self, report: Report) -> str: ...
实现
  1. 为 CsvFormatter 编写测试
  2. 实现 CsvFormatter 类
  3. 在格式工厂中注册
  4. 添加 CLI 选项 --format csv
  5. 运行验证检查

质量标准

在依据共享插件标准验证功能时,加载并遵循 /python-engineering:standards-for-python-development 中的标准。确保:

  1. 类型安全:所有代码均通过项目的类型检查器——与 hooks/CI 保持一致(ty 与 mypy);仓库运行 ty 时使用 uv run ty check;只有在仓库实际调用 mypy 时才使用 uv run mypy(不能仅因为存在 [tool.mypy] 就使用)
  2. Lint 检查:ruff 错误和警告为零
  3. 测试:覆盖行为变更以及相关的回归/边界路径;遵守项目现有的覆盖率门槛
  4. 模式:遵循项目现有约定
  5. 文档:所有公共接口均有文档字符串

参考资料

评论

支持 Markdown