displayName: "Python编程规范" version: "1.0.1" slug: "self-dev-python" name: python description: "Python编程规范与最佳实践。强制PEP 8代码风格、语法校验、单元测试执行,适用于代码编写、审查和重构。触发词:Python、代码规范、py_compile、单元测试。"
# Syntax check (always)
python -m py_compile *.py
# Run tests if present
python -m pytest tests/ -v 2>/dev/null || python -m unittest discover -v 2>/dev/null || echo "No tests found"
# Format check (if available)
ruff check . --fix 2>/dev/null || python -m black --check . 2>/dev/null
Check for uv first, fall back to pip:
# Prefer uv if available
if command -v uv &>/dev/null; then
uv pip install <package>
uv pip compile requirements.in -o requirements.txt
else
pip install <package>
fi
For new projects with uv: uv init or uv venv && source .venv/bin/activate
# ✅ List/dict comprehensions over loops squares = [x**2 for x in range(10)] lookup = {item.id: item for item in items} # ✅ Context managers for resources with open("file.txt") as f: data = f.read() # ✅ Unpacking first, *rest = items a, b = b, a # swap # ✅ EAFP over LBYL try: value = d[key] except KeyError: value = default # ✅ f-strings for formatting msg = f"Hello {name}, you have {count} items" # ✅ Type hints def process(items: list[str]) -> dict[str, int]: ... # ✅ dataclasses/attrs for data containers from dataclasses import dataclass @dataclass class User: name: str email: str active: bool = True # ✅ pathlib over 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): ...7w4.net提供免费和付费技能下载。
# ❌ Mutable default arguments
def bad(items=[]): # Bug: shared across calls
...
def good(items=None):
items = items or []
# ❌ Bare except
try:
...
except: # Catches SystemExit, KeyboardInterrupt
...
except Exception: # Better
...
# ❌ Global state
# ❌ from module import *
# ❌ String concatenation in loops (use join)
# ❌ == None (use `is None`)
# ❌ len(x) == 0 (use `not x`)
test_*.py, test functions test_*python -m pytest -vdef fetch_user(user_id: int, include_deleted: bool = False) -> User | None:
"""Fetch a user by ID from the database.
Args:
user_id: The unique user identifier.
include_deleted: If True, include soft-deleted users.
Returns:
User object if found, None otherwise.
Raises:
DatabaseError: If connection fails.
"""
py_compile)pytest).format() or %pathlib for file paths这个 Skill 质量较好,内容全面且实用,涵盖了 Python 开发的各个方面,用大量代码示例清晰展示正确和错误的写法,检查清单也很实用。不足之处是缺少一些可直接使用的工具配置,以及具体的代码响应示例,新手使用时可能需要额外查阅文档。