返回顶部
p

pythonPython编码规范

Python coding guidelines and best practices. Use when writing, reviewing, or refactoring Python code. Enforces PEP 8 style, syntax validation via py_compile, unit test execution, modern Python versions only (no EOL), uv for dependency management when available, and idiomatic Pythonic patterns.

作者: admin | 来源: ClawHub
源自
ClawHub
版本
V 1.0.0
安全检测
已通过
8,502
下载量
免费
免费
8
收藏
概述
安装方式
版本历史

python

Python 编码指南

代码风格(PEP 8)

  • - 缩进使用4个空格(绝不使用制表符)
  • 最大行长度:88字符(Black默认)或79字符(严格PEP 8)
  • 顶层定义前空两行,类内部方法间空一行
  • 导入顺序:标准库 → 第三方库 → 本地库,每组内按字母排序
  • 函数/变量使用蛇形命名法,类使用帕斯卡命名法,常量使用全大写命名法

提交前检查

bash

语法检查(始终执行)


python -m py_compile *.py

运行测试(如存在)

python -m pytest tests/ -v 2>/dev/null || python -m unittest discover -v 2>/dev/null || echo 未找到测试

格式检查(如可用)

ruff check . --fix 2>/dev/null || python -m black --check . 2>/dev/null

Python 版本

  • - 最低要求: Python 3.10+(Python 3.9 将于2025年10月停止支持)
  • 目标版本: 新项目使用 Python 3.11-3.13
  • 绝不使用 Python 2 语法或模式
  • 使用现代特性:match语句、海象运算符、类型提示

依赖管理

优先检查 uv,回退到 pip:
bash

优先使用 uv(如可用)


if command -v uv &>/dev/null; then
uv pip install <包名>
uv pip compile requirements.in -o requirements.txt
else
pip install <包名>
fi

使用 uv 创建新项目:uv init 或 uv venv && source .venv/bin/activate

Python 惯用模式

python

✅ 列表/字典推导式优于循环


squares = [x2 for x in range(10)]
lookup = {item.id: item for item in items}

✅ 使用上下文管理器管理资源

with open(file.txt) as f: data = f.read()

✅ 解包操作

first, *rest = items a, b = b, a # 交换变量

✅ 请求宽恕比请求许可更容易(EAFP)优于三思而后行(LBYL)

try: value = d[key] except KeyError: value = default

✅ 使用 f-string 进行格式化

msg = f你好 {name},你有 {count} 个项目

✅ 类型提示

def process(items: list[str]) -> dict[str, int]: ...

✅ 使用数据类/属性类作为数据容器

from dataclasses import dataclass

@dataclass
class User:
name: str
email: str
active: bool = True

✅ 使用 pathlib 替代 os.path

from pathlib import Path config = Path.home() / .config / app.json

✅ 使用 enumerate、zip、itertools

for i, item in enumerate(items): ... for a, b in zip(list1, list2, strict=True): ...

应避免的反模式

python

❌ 可变默认参数


def bad(items=[]): # 错误:在多次调用间共享
...
def good(items=None):
items = items or []

❌ 裸 except

try: ... except: # 会捕获 SystemExit、KeyboardInterrupt ... except Exception: # 更好的做法 ...

❌ 全局状态

❌ from module import *

❌ 在循环中拼接字符串(应使用 join)

❌ == None(应使用 is None)

❌ len(x) == 0(应使用 not x)

测试

  • - 使用 pytest(推荐)或 unittest
  • 测试文件命名为 test.py,测试函数命名为 test
  • 目标:聚焦的单元测试,模拟外部依赖
  • 每次提交前运行:python -m pytest -v

文档字符串

python
def fetchuser(userid: int, include_deleted: bool = False) -> User | None:
根据用户ID从数据库获取用户。

参数:
user_id: 用户唯一标识符。
include_deleted: 如果为True,则包含软删除的用户。

返回:
找到则返回用户对象,否则返回None。

抛出异常:
DatabaseError: 如果数据库连接失败。

快速检查清单

  • - [ ] 语法有效(py_compile)
  • [ ] 测试通过(pytest)
  • [ ] 公开函数有类型提示
  • [ ] 无硬编码密钥
  • [ ] 使用 f-string,而非 .format() 或 %
  • [ ] 使用 pathlib 处理文件路径
  • [ ] 使用上下文管理器处理 I/O 操作
  • [ ] 无可变默认参数

标签

skill ai

通过对话安装

该技能支持在以下平台通过对话安装:

OpenClaw WorkBuddy QClaw Kimi Claude

方式一:安装 SkillHub 和技能

帮我安装 SkillHub 和 python-1776090662 技能

方式二:设置 SkillHub 为优先技能安装源

设置 SkillHub 为我的优先技能安装源,然后帮我安装 python-1776090662 技能

通过命令行安装

skillhub install python-1776090662

下载

⬇ 下载 python v1.0.0(免费)

文件大小: 2.45 KB | 发布时间: 2026-4-15 14:03

v1.0.0 最新 2026-4-15 14:03
Initial release providing Python coding guidelines and best practices.

- Enforces PEP 8 style and modern, Pythonic patterns.
- Requires Python 3.10+; promotes use of features from Python 3.11–3.13.
- Includes syntax validation, unit test execution, and automatic formatting before commits.
- Recommends `uv` for dependency management if available, with `pip` as fallback.
- Documents clear Pythonic patterns, anti-patterns, and testing practices.
- Provides a concise checklist for code readiness and best practices.

Archiver·手机版·闲社网·闲社论坛·羊毛社区· 多链控股集团有限公司 · 苏ICP备2025199260号-1

Powered by Discuz! X5.0   © 2024-2025 闲社网·线报更新论坛·羊毛分享社区·http://xianshe.com

p2p_official_large
返回顶部