name: python description: 使用高级功能编写地道的Python代码。适用于Python开发、重构或优化。
Python开发
编写清洁、高效、地道的Python代码。
使用场景
- 编写Python代码
- 重构Python项目
- 性能优化
- 设置Python工具链
- Python代码审查
Python最佳实践
代码风格
- 遵循PEP 8
- 使用类型提示(Python 3.9+)
- 优先使用f-字符串而非.format()
- 使用pathlib而非os.path
现代特性
# 类型提示
def process(data: list[dict]) -> dict[str, int]:
...
# 数据类
from dataclasses import dataclass
@dataclass
class User:
name: str
email: str
active: bool = True
# 上下文管理器
from contextlib import contextmanager
@contextmanager
def timer():
start = time.time()
yield
print(f"耗时: {time.time() - start:.2f}s")
# 生成器用于内存效率
def read_large_file(path):
with open(path) as f:
yield from f
错误处理
# 自定义异常
class ValidationError(Exception):
def __init__(self, field: str, message: str):
self.field = field
self.message = message
super().__init__(f"{field}: {message}")
# 正确的异常链
try:
process()
except ValueError as e:
raise ProcessingError("处理失败") from e
项目结构
project/
├── src/
│ └── package/
│ ├── __init__.py
│ └── module.py
├── tests/
│ └── test_module.py
├── pyproject.toml
└── README.md
工具设置
# pyproject.toml
[tool.ruff]
line-length = 88
select = ["E", "F", "I", "UP"]
[tool.mypy]
strict = true
[tool.pytest.ini_options]
testpaths = ["tests"]
测试模式
import pytest
@pytest.fixture
def sample_data():
return {"key": "value"}
def test_process(sample_data):
result = process(sample_data)
assert result["status"] == "success"
示例
输入: “重构这段Python代码” 操作: 应用PEP 8,添加类型提示,简化逻辑,改进错误处理
输入: “让它更快” 操作: 分析性能,识别瓶颈,使用生成器/缓存,验证改进