python-development by laurigates/claude-plugins
npx skills add https://github.com/laurigates/claude-plugins --skill python-developmentPython 核心语言概念、惯用法和最佳实践。
# 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]
"""使用现代类型提示处理项目。"""
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"}
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"
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
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)
# 文件处理
with open("file.txt") as f:
content = f.read()
# 自定义上下文管理器
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")
# 列表推导式
squares = [x**2 for x in range(10)]
# 字典推导式
word_lengths = {word: len(word) for word in ["hello", "world"]}
# 集合推导式
unique_lengths = {len(word) for word in ["hello", "world", "hi"]}
# 生成器表达式
sum_of_squares = sum(x**2 for x in range(1000000)) # 内存高效
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
# 使用生成器
fib = fibonacci()
first_ten = [next(fib) for _ in range(10)]
# 生成器表达式
even_squares = (x**2 for x in range(10) if x % 2 == 0)
import pdb
def problematic_function():
value = calculate()
pdb.set_trace() # 调试器断点
return process(value)
# 出错时调试
python -m pdb script.py
# 使用调试器的 pytest
uv run pytest --pdb # 失败时进入 pdb
uv run pytest --pdb --pdbcls=IPython.terminal.debugger:TerminalPdb
# CPU 性能分析
uv run python -m cProfile -s cumtime script.py | head -20
# 逐行性能分析(临时依赖)
uv run --with line-profiler kernprof -l -v script.py
# 内存分析(临时依赖)
uv run --with memory-profiler python -m memory_profiler script.py
# 实时性能分析(临时工具)
uvx py-spy top -- python script.py
# 使用 scalene 快速分析
uv run --with scalene python -m scalene script.py
# 跟踪执行
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)
# 内存跟踪
import tracemalloc
tracemalloc.start()
# ... 要分析的代码
snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics('lineno')
for stat in top_stats[:10]:
print(stat)
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():
# 并发运行
results = await asyncio.gather(
fetch_data("url1"),
fetch_data("url2"),
fetch_data("url3"),
)
return results
# 带超时
async def with_timeout():
try:
result = await asyncio.wait_for(fetch_data("url"), timeout=5.0)
except asyncio.TimeoutError:
print("请求超时")
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"未知处理器: {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__} 耗时 {end - start:.2f}s")
return result
return wrapper
@timer
def slow_function():
time.sleep(1)
单一职责原则:
# 不好:类承担了太多职责
class User:
def save(self): pass
def send_email(self): pass
def generate_report(self): pass
# 好:职责分离
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:
# 尽早验证
if not data:
raise ValueError("数据不能为空")
if "required_field" not in data:
raise KeyError("缺少必填字段")
# 放心处理
return data["required_field"].upper()
# 优先使用不可变转换
def process_items(items: list[int]) -> list[int]:
return [item * 2 for item in items] # 新列表
# 而不是修改原数据
def process_items_bad(items: list[int]) -> None:
for i in range(len(items)):
items[i] *= 2 # 修改输入
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
每周安装量
106
代码仓库
GitHub 星标数
19
首次出现
2026年1月29日
安全审计
安装于
opencode103
github-copilot102
codex101
gemini-cli100
kimi-cli100
amp100
Core Python language concepts, idioms, and best practices.
# 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"}
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)
# 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)
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)
Single Responsibility:
# 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
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
Weekly Installs
106
Repository
GitHub Stars
19
First Seen
Jan 29, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
opencode103
github-copilot102
codex101
gemini-cli100
kimi-cli100
amp100
agent-browser 浏览器自动化工具 - Vercel Labs 命令行网页操作与测试
157,400 周安装
Gemini Live API 开发指南:实时语音视频交互、WebSockets集成与SDK使用
1,500 周安装
Tavily AI 网站爬取工具 - 智能提取文档、知识库和全站内容
3,500 周安装
Vue.js测试最佳实践:Vue 3组件、组合式函数、Pinia与异步测试完整指南
4,000 周安装
Google Workspace CLI 教程:使用 gws 命令创建反馈表单并邮件分享
7,200 周安装
Google Workspace 事件订阅命令 gws-events-subscribe:实时流式监控与自动化处理
7,500 周安装
Google Calendar 会议重新安排技能 - 自动更新会议时间并通知参与者
7,500 周安装