generating-python-code

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Generating 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 delivery
1. 检查先决条件 → 若复杂度为中等及以上,需确认已有设计方案
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
designing-systems
skill first.
编写代码前:
  • 已有设计方案,或复杂度为 trivial/低
  • 明确要构建的内容(不仅是实现方式)
  • 依赖关系清晰
若复杂度为中等及以上,请先使用
designing-systems
技能。

Mandatory 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
undefined

RIGHT - 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(): ...

```python

WRONG - 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
undefined
python
undefined

WRONG

错误示例

def process(data): return data.upper()
def process(data): return data.upper()

RIGHT

正确示例

def process(data: str) -> str: return data.upper()
undefined
def process(data: str) -> str: return data.upper()
undefined

Docstrings (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

命名规范

ElementConventionExample
ClassesPascalCase, noun
OrderProcessor
Functionssnake_case, verb+noun
calculate_total
ConstantsUPPER_SNAKE
MAX_RETRIES
Private_prefix
_validate_input
元素规范示例
PascalCase,名词
OrderProcessor
函数snake_case,动词+名词
calculate_total
常量UPPER_SNAKE
MAX_RETRIES
私有成员前缀加_
_validate_input

Forbidden Names

禁用名称

data
,
info
,
manager
,
handler
,
util
,
helper
,
misc
,
process
(too generic)
data
info
manager
handler
util
helper
misc
process
(过于通用)

Error Handling Pattern

错误处理模式

python
undefined
python
undefined

WRONG - 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
undefined
def get_user(user_id: str) -> User: user = db.find(user_id) if not user: raise UserNotFoundError(f"未找到用户 {user_id}") return user
undefined

Function 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

禁用模式

PatternWhy BadFix
except Exception
Swallows all errorsCatch specific exceptions
return None
for errors
Caller forgets to checkRaise domain exception
if isinstance(x, Type)
chains
Type-based branchingUse polymorphism
Global mutable stateUntestable, race conditionsInject dependencies
String concatenation for SQLSQL injectionUse parameterized queries
Hard-coded config valuesInflexibleUse environment/config
模式弊端修复方案
except Exception
吞噬所有错误捕获特定异常
错误时返回
None
调用方可能忘记检查抛出领域异常
if isinstance(x, Type)
链式判断
基于类型分支,扩展性差使用多态
全局可变状态不可测试,存在竞态条件注入依赖
字符串拼接SQL语句存在SQL注入风险使用参数化查询
硬编码配置值灵活性差使用环境变量/配置文件

Validation Script

验证脚本

After generating code, validate structure:
bash
python scripts/validate_structure.py generated_file.py
This 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 dataclass
python
"""
模块文档字符串,说明模块用途。
"""
from __future__ import annotations

from typing import Protocol
from dataclasses import dataclass

Interfaces first

先定义接口

class IRepository(Protocol): ...
class IRepository(Protocol): ...

Value Objects

值对象

@dataclass(frozen=True) class Money: ...
@dataclass(frozen=True) class Money: ...

Domain classes

领域类

class Service: ...
undefined
class Service: ...
undefined

After Generation

生成后步骤

  • Run
    validate_structure.py
    to check standards
  • Use
    securing-code
    skill before delivery
  • 运行
    validate_structure.py
    检查是否符合标准
  • 交付前使用
    securing-code
    技能