关于 python
面向 Python 开发的编码规范技能,涵盖类型标注、项目结构、测试和工具配置,帮助团队建立一致的开发与质量检查流程。
主要功能
- 01函数签名使用类型标注
- 02按职责组织项目结构
- 03配置 Ruff 与 mypy
- 04使用 pytest 编写测试
- 05采用 Pydantic 数据验证
- 06遵循依赖注入与 Result 模式
适用场景
- 01启动新的 Python 项目
- 02为代码库统一质量规范
- 03设置自动化测试与 CI 检查
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ alinaqi/ maggy --skill python安装后在 Claude Code 中输入/python确认已加载。
详细介绍
Python 技能
类型提示
- 所有函数签名都要使用类型提示
- 复杂类型使用
typing模块 - 在 CI 中运行
mypy --strict
def process_user(user_id: int, options: dict[str, Any] | None = None) -> User:
...
项目结构
project/
├── src/
│ └── package_name/
│ ├── __init__.py
│ ├── core/ # Pure business logic
│ │ ├── __init__.py
│ │ ├── models.py # Pydantic models / dataclasses
│ │ └── services.py # Pure functions
│ ├── infra/ # Side effects
│ │ ├── __init__.py
│ │ ├── api.py # FastAPI routes
│ │ └── db.py # Database operations
│ └── utils/ # Shared utilities
├── tests/
│ ├── unit/
│ └── integration/
├── pyproject.toml
└── CLAUDE.md
工具(必需)
# pyproject.toml
[tool.ruff]
line-length = 100
select = ["E", "F", "I", "N", "W", "UP"]
[tool.mypy]
strict = true
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "--cov=src --cov-report=term-missing --cov-fail-under=80"
使用 Pytest 进行测试
# tests/unit/test_services.py
import pytest
from package_name.core.services import calculate_total
class TestCalculateTotal:
def test_returns_sum_of_items(self):
# Arrange
items = [{"price": 10}, {"price": 20}]
# Act
result = calculate_total(items)
# Assert
assert result == 30
def test_returns_zero_for_empty_list(self):
assert calculate_total([]) == 0
def test_raises_on_invalid_item(self):
with pytest.raises(ValueError):
calculate_total([{"invalid": "item"}])
GitHub Actions
name: Python Quality Gate
on: [push, pull_request]
jobs:
quality:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Python
uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: Install dependencies
run: |
pip install -e ".[dev]"
- name: Lint (Ruff)
run: ruff check .
- name: Format Check (Ruff)
run: ruff format --check .
- name: Type Check (mypy)
run: mypy src/
- name: Test with Coverage
run: pytest
Pre-Commit 钩子
# .pre-commit-config.yaml
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.8.0
hooks:
- id: ruff
args: [--fix]
- id: ruff-format
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.13.0
hooks:
- id: mypy
additional_dependencies: [pydantic]
args: [--strict]
- repo: local
hooks:
- id: pytest
name: pytest
entry: pytest tests/unit -x --tb=short
language: system
pass_filenames: false
always_run: true
安装和设置:
pip install pre-commit
pre-commit install
模式
使用 Pydantic 进行数据验证
from pydantic import BaseModel, Field
class CreateUserRequest(BaseModel):
email: str = Field(..., min_length=5)
name: str = Field(..., max_length=100)
依赖注入
# Don't import dependencies directly in business logic
# Pass them in
# Bad
from .db import database
def get_user(user_id: int) -> User:
return database.fetch(user_id)
# Good
def get_user(user_id: int, db: Database) -> User:
return db.fetch(user_id)
Result 模式(核心代码中不使用异常)
from dataclasses import dataclass
@dataclass
class Result[T]:
value: T | None
error: str | None
@property
def is_ok(self) -> bool:
return self.error is None
Python 反模式
- ❌
from module import * - ❌ 可变默认参数
- ❌ 裸
except:子句 - ❌ 使用
type: ignore却不作说明 - ❌ 使用全局变量保存状态
- ❌ 能用函数实现时却使用类
评论
支持 Markdown