关于 python-development
python-development 为编写现代 Python 3.10+ 代码提供语言知识与实践指导,面向开发者和库作者。内容涵盖类型标注、异步编程、调试、性能分析及 Pythonic 设计;项目初始化、测试和单次脚本运行另有专门技能。
主要功能
- 01Python 3.10+ 语言特性
- 02类型标注与装饰器
- 03async/await 与 asyncio
- 04调试和性能分析
- 05Pythonic 设计实践
适用场景
- 01为库代码添加类型标注
- 02设计异步任务流程
- 03调试并分析代码性能
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ laurigates/ claude-plugins --skill python-development安装后在 Claude Code 中输入/python-development确认已加载。
附带文件REFERENCE.md
详细介绍
Python 开发
Python 语言核心概念、惯用法和最佳实践。
何时使用此技能
| 适用情况…… | 以下情况请改用专门的同类技能…… |
|---|---|
| 编写符合惯例的 Python 3.10+ 代码(match 语句、结构化模式匹配、PEP 604 联合类型) | 运行单个脚本或一次性命令——使用 uv-run |
| 为库代码添加类型提示、装饰器或上下文管理器 | 初始化项目或添加依赖项——使用 uv-project-management |
| 设计 async/await 流程,或重构为符合 Python 惯例的模式 | 编写或运行 pytest 测试——使用 python-testing |
核心专长
- Python 语言:现代 Python 3.10+ 特性和惯用法
- 最佳实践:Pythonic 代码、设计模式、SOLID 原则
- 调试:交互式调试和性能分析技术
- 性能:优化策略和性能分析
- 异步编程:async/await 模式和 asyncio
现代 Python 特性(3.10+)
类型提示
# Modern syntax (Python 3.10+)
def process_items(
items: list[str], # Not List[str]
mapping: dict[str, int], # Not Dict[str, int]
optional: str | None = None, # Not Optional[str]
) -> tuple[bool, str]: # Not Tuple[bool, str]
"""Process items with modern type hints."""
return True, "success"
# Type aliases
type UserId = int
type UserDict = dict[str, str | int]
def get_user(user_id: UserId) -> UserDict:
return {"id": user_id, "name": "Alice"}
模式匹配(3.10+)
def handle_command(command: dict) -> str:
match command:
case {"action": "create", "item": item}:
return f"Creating {item}"
case {"action": "delete", "item": item}:
return f"Deleting {item}"
case {"action": "list"}:
return "Listing items"
case _:
return "Unknown command"
结构化模式匹配
def process_response(response):
match response:
case {"status": 200, "data": data}:
return process_success(data)
case {"status": 404}:
raise NotFoundError()
case {"status": code} if code >= 500:
raise ServerError(code)
Python 惯用法
上下文管理器
# File handling
with open("file.txt") as f:
content = f.read()
# Custom context manager
from contextlib import contextmanager
@contextmanager
def database_connection():
conn = create_connection()
try:
yield conn
finally:
conn.close()
with database_connection() as conn:
conn.execute("SELECT * FROM users")
列表推导式
# List comprehension
squares = [x**2 for x in range(10)]
# Dict comprehension
word_lengths = {word: len(word) for word in ["hello", "world"]}
# Set comprehension
unique_lengths = {len(word) for word in ["hello", "world", "hi"]}
# Generator expression
sum_of_squares = sum(x**2 for x in range(1000000)) # Memory efficient
迭代器和生成器
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
# Use generator
fib = fibonacci()
first_ten = [next(fib) for _ in range(10)]
# Generator expression
even_squares = (x**2 for x in range(10) if x % 2 == 0)
调试
交互式调试
import pdb
def problematic_function():
value = calculate()
pdb.set_trace() # Debugger breakpoint
return process(value)
# Debug on error
python -m pdb script.py
# pytest with debugger
uv run pytest --pdb # Drop into pdb on failure
uv run pytest --pdb --pdbcls=IPython.terminal.debugger:TerminalPdb
性能分析
# CPU profiling
uv run python -m cProfile -s cumtime script.py | head -20
# Line-by-line profiling (temporary dependency)
uv run --with line-profiler kernprof -l -v script.py
# Memory profiling (temporary dependency)
uv run --with memory-profiler python -m memory_profiler script.py
# Real-time profiling (ephemeral tool)
uvx py-spy top -- python script.py
# Quick profiling with scalene
uv run --with scalene python -m scalene script.py
内置调试工具
# Trace execution
import sys
def trace_calls(frame, event, arg):
if event == 'call':
print(f"Calling {frame.f_code.co_name}")
return trace_calls
sys.settrace(trace_calls)
# Memory tracking
import tracemalloc
tracemalloc.start()
# ... code to profile
snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics('lineno')
for stat in top_stats[:10]:
print(stat)
异步编程
基本 async/await
import asyncio
async def fetch_data(url: str) -> dict:
async with httpx.AsyncClient() as client:
response = await client.get(url)
return response.json()
async def main():
result = await fetch_data("https://api.example.com")
print(result)
asyncio.run(main())
并发任务
async def process_multiple():
# Run concurrently
results = await asyncio.gather(
fetch_data("url1"),
fetch_data("url2"),
fetch_data("url3"),
)
return results
# With timeout
async def with_timeout():
try:
result = await asyncio.wait_for(fetch_data("url"), timeout=5.0)
except asyncio.TimeoutError:
print("Request timed out")
设计模式
依赖注入
from typing import Protocol
class Database(Protocol):
def query(self, sql: str) -> list: ...
def get_users(db: Database) -> list:
return db.query("SELECT * FROM users")
工厂模式
def create_handler(handler_type: str):
match handler_type:
case "json":
return JSONHandler()
case "xml":
return XMLHandler()
case _:
raise ValueError(f"Unknown handler: {handler_type}")
装饰器模式
from functools import wraps
import time
def timer(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} took {end - start:.2f}s")
return result
return wrapper
@timer
def slow_function():
time.sleep(1)
最佳实践
SOLID 原则
单一职责:
# Bad: Class does too much
class User:
def save(self): pass
def send_email(self): pass
def generate_report(self): pass
# Good: Separate concerns
class User:
def save(self): pass
class EmailService:
def send_email(self, user): pass
class ReportGenerator:
def generate(self, user): pass
快速失败
def process_data(data: dict) -> str:
# Validate early
if not data:
raise ValueError("Data cannot be empty")
if "required_field" not in data:
raise KeyError("Missing required field")
# Process with confidence
return data["required_field"].upper()
函数式方法
# Prefer immutable transformations
def process_items(items: list[int]) -> list[int]:
return [item * 2 for item in items] # New list
# Over mutations
def process_items_bad(items: list[int]) -> None:
for i in range(len(items)):
items[i] *= 2 # Mutates input
项目结构(src 布局)
my-project/
├── pyproject.toml
├── README.md
├── src/
│ └── my_project/
│ ├── __init__.py
│ ├── core.py
│ ├── utils.py
│ └── models.py
└── tests/
├── conftest.py
├── test_core.py
└── test_utils.py
另请参阅
- uv-run - 运行脚本、临时依赖项、PEP 723
- uv-project-management - 项目设置和依赖项管理
- uv-tool-management - 全局安装 CLI 工具
- python-testing - 使用 pytest 进行测试
- python-code-quality - 使用 ruff/ty 进行代码检查和类型检查
- python-packaging - 构建和发布包
- uv-python-versions - 管理 Python 解释器
参考资料
- Python 文档:https://docs.python.org/3/
- 类型提示:https://docs.python.org/3/library/typing.html
- 异步编程:https://docs.python.org/3/library/asyncio.html
- 详细指南:请参阅 REFERENCE.md
评论
支持 Markdown