generating-python-code
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGenerating Python Code
生成Python代码
Workflow
工作流程
1. CHECK PREREQUISITES → Verify design exists if Medium+
2. APPLY STANDARDS → Type hints, docstrings, naming
3. IMPLEMENT → Write code following patterns
4. VALIDATE → Run validate_structure.py
5. SECURE → Use securing-code skill before delivery1. 检查先决条件 → 若复杂度为中等及以上,需确认已有设计方案
2. 应用标准 → 类型提示、文档字符串、命名规范
3. 实现代码 → 遵循模式编写代码
4. 验证 → 运行validate_structure.py
5. 安全加固 → 交付前使用securing-code技能Pre-Generation Checklist
生成前检查清单
Before writing code:
- Design exists or complexity is Trivial/Low
- I know WHAT to build (not just HOW)
- Dependencies are clear
If complexity is Medium+, use skill first.
designing-systems编写代码前:
- 已有设计方案,或复杂度为 trivial/低
- 明确要构建的内容(不仅是实现方式)
- 依赖关系清晰
若复杂度为中等及以上,请先使用技能。
designing-systemsMandatory Code Standards
强制代码标准
Import Organization (PEP 8)
导入组织(PEP 8)
ALL imports MUST be at the top of the file, after the module docstring and before any other code.
python
undefined所有导入必须放在文件顶部,位于模块文档字符串之后、其他代码之前。
python
undefinedRIGHT - Imports at the top, organized
正确示例 - 导入放在顶部并有序组织
"""Module docstring."""
from future import annotations
import os
import sys
from typing import Protocol
from third_party import SomeClass
from myproject.domain import Entity
def my_function():
...
```python"""模块文档字符串。"""
from future import annotations
import os
import sys
from typing import Protocol
from third_party import SomeClass
from myproject.domain import Entity
def my_function():
...
```pythonWRONG - Imports scattered in code
错误示例 - 导入分散在代码中
def process_data():
import json # NEVER import inside functions
...
def another_function():
try:
from module import thing # NEVER import inside try/except
except ImportError:
thing = None
**Import order (isort standard):**
1. `__future__` imports
2. Standard library imports
3. Third-party imports
4. Local application imports
Each group separated by a blank line.def process_data():
import json # 绝对不要在函数内导入
...
def another_function():
try:
from module import thing # 绝对不要在try/except内导入
except ImportError:
thing = None
**导入顺序(isort标准):**
1. `__future__` 导入
2. 标准库导入
3. 第三方库导入
4. 本地应用导入
每组导入之间用空行分隔。Type Hints (ALWAYS)
类型提示(必须添加)
python
undefinedpython
undefinedWRONG
错误示例
def process(data):
return data.upper()
def process(data):
return data.upper()
RIGHT
正确示例
def process(data: str) -> str:
return data.upper()
undefineddef process(data: str) -> str:
return data.upper()
undefinedDocstrings (Public APIs)
文档字符串(公共API)
python
def calculate_total(items: list[LineItem], tax_rate: Decimal) -> Money:
"""Calculate order total including tax.
Args:
items: Line items with price and quantity
tax_rate: Tax rate as decimal (0.21 for 21%)
Returns:
Total amount as Money value object
Raises:
InvalidTaxRateError: If tax_rate is negative
"""python
def calculate_total(items: list[LineItem], tax_rate: Decimal) -> Money:
"""计算包含税费的订单总额。
参数:
items: 包含价格和数量的订单项
tax_rate: 税率(十进制,如21%对应0.21)
返回:
总额,以Money值对象形式返回
异常:
InvalidTaxRateError: 若税率为负数时抛出
"""Naming Conventions
命名规范
| Element | Convention | Example |
|---|---|---|
| Classes | PascalCase, noun | |
| Functions | snake_case, verb+noun | |
| Constants | UPPER_SNAKE | |
| Private | _prefix | |
| 元素 | 规范 | 示例 |
|---|---|---|
| 类 | PascalCase,名词 | |
| 函数 | snake_case,动词+名词 | |
| 常量 | UPPER_SNAKE | |
| 私有成员 | 前缀加_ | |
Forbidden Names
禁用名称
datainfomanagerhandlerutilhelpermiscprocessdatainfomanagerhandlerutilhelpermiscprocessError Handling Pattern
错误处理模式
python
undefinedpython
undefinedWRONG - Silent failure
错误示例 - 静默失败
def get_user(user_id: str) -> User | None:
user = db.find(user_id)
return user # Caller might forget to check None
def get_user(user_id: str) -> User | None:
user = db.find(user_id)
return user # 调用方可能会忘记检查None
RIGHT - Explicit failure
正确示例 - 显式失败
def get_user(user_id: str) -> User:
user = db.find(user_id)
if not user:
raise UserNotFoundError(f"User {user_id} not found")
return user
undefineddef get_user(user_id: str) -> User:
user = db.find(user_id)
if not user:
raise UserNotFoundError(f"未找到用户 {user_id}")
return user
undefinedFunction Rules
函数规则
- Max 20 lines (ideal: 5-10)
- Max 3 parameters (use dataclass/TypedDict for more)
- No boolean flags as parameters
- Single responsibility
- 最多20行(理想范围:5-10行)
- 最多3个参数(参数更多时使用dataclass/TypedDict)
- 禁止使用布尔标志作为参数
- 遵循单一职责原则
Prohibited Patterns
禁用模式
| Pattern | Why Bad | Fix |
|---|---|---|
| Swallows all errors | Catch specific exceptions |
| Caller forgets to check | Raise domain exception |
| Type-based branching | Use polymorphism |
| Global mutable state | Untestable, race conditions | Inject dependencies |
| String concatenation for SQL | SQL injection | Use parameterized queries |
| Hard-coded config values | Inflexible | Use environment/config |
| 模式 | 弊端 | 修复方案 |
|---|---|---|
| 吞噬所有错误 | 捕获特定异常 |
错误时返回 | 调用方可能忘记检查 | 抛出领域异常 |
| 基于类型分支,扩展性差 | 使用多态 |
| 全局可变状态 | 不可测试,存在竞态条件 | 注入依赖 |
| 字符串拼接SQL语句 | 存在SQL注入风险 | 使用参数化查询 |
| 硬编码配置值 | 灵活性差 | 使用环境变量/配置文件 |
Validation Script
验证脚本
After generating code, validate structure:
bash
python scripts/validate_structure.py generated_file.pyThis checks: type hints present, function length, naming conventions.
生成代码后,验证结构:
bash
python scripts/validate_structure.py generated_file.py该脚本会检查:是否存在类型提示、函数长度、命名规范。
Examples
示例
For complete input/output examples → See reference/examples.md
For what NOT to do → See reference/anti-patterns.md
完整输入/输出示例 → 参见reference/examples.md
反面示例 → 参见reference/anti-patterns.md
Output Format
输出格式
python
"""
Module docstring explaining purpose.
"""
from __future__ import annotations
from typing import Protocol
from dataclasses import dataclasspython
"""
模块文档字符串,说明模块用途。
"""
from __future__ import annotations
from typing import Protocol
from dataclasses import dataclassInterfaces first
先定义接口
class IRepository(Protocol):
...
class IRepository(Protocol):
...
Value Objects
值对象
@dataclass(frozen=True)
class Money:
...
@dataclass(frozen=True)
class Money:
...
Domain classes
领域类
class Service:
...
undefinedclass Service:
...
undefinedAfter Generation
生成后步骤
- Run to check standards
validate_structure.py - Use skill before delivery
securing-code
- 运行检查是否符合标准
validate_structure.py - 交付前使用技能
securing-code