关于 python-development
面向 Python 开发者的技能,帮助搭建和维护 Python 项目,内容涵盖项目结构、类型标注、异步代码、FastAPI、测试和工具实践。
主要功能
- 01现代项目结构
- 02类型标注与泛型
- 03异步 I/O 模式
- 04FastAPI 示例
- 05pytest 测试模式
- 06代码检查与类型检查建议
适用场景
- 01规划 Python 项目结构
- 02为 Python 代码添加类型
- 03编写异步 I/O 逻辑
- 04测试 FastAPI 应用
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ moizibnyousaf/ ai-agent-skills --skill python-development安装后在 Claude Code 中输入/python-development确认已加载。
详细介绍
Python 开发
项目设置
现代 Python 项目结构
my-project/
├── src/
│ └── my_project/
│ ├── __init__.py
│ ├── main.py
│ └── utils.py
├── tests/
│ ├── __init__.py
│ └── test_main.py
├── pyproject.toml
├── README.md
└── .gitignore
pyproject.toml
[project]
name = "my-project"
version = "0.1.0"
requires-python = ">=3.12"
dependencies = [
"fastapi>=0.100.0",
"pydantic>=2.0",
]
[project.optional-dependencies]
dev = [
"pytest>=7.0",
"ruff>=0.1.0",
"mypy>=1.0",
]
[tool.ruff]
line-length = 88
select = ["E", "F", "I", "N", "W"]
[tool.mypy]
strict = true
类型提示
from typing import TypeVar, Generic
from collections.abc import Sequence
T = TypeVar('T')
def process_items(items: Sequence[str]) -> list[str]:
return [item.upper() for item in items]
class Repository(Generic[T]):
def get(self, id: int) -> T | None: ...
def save(self, item: T) -> T: ...
异步模式
import asyncio
from collections.abc import AsyncIterator
async def fetch_all(urls: list[str]) -> list[dict]:
async with aiohttp.ClientSession() as session:
tasks = [fetch_one(session, url) for url in urls]
return await asyncio.gather(*tasks)
async def stream_data() -> AsyncIterator[bytes]:
async with aiofiles.open('large_file.txt', 'rb') as f:
async for chunk in f:
yield chunk
FastAPI 模式
from fastapi import FastAPI, Depends, HTTPException
from pydantic import BaseModel
app = FastAPI()
class UserCreate(BaseModel):
email: str
name: str
class UserResponse(BaseModel):
id: int
email: str
name: str
@app.post("/users", response_model=UserResponse)
async def create_user(
user: UserCreate,
db: Database = Depends(get_db)
) -> UserResponse:
result = await db.users.create(user.model_dump())
return UserResponse(**result)
测试
import pytest
from unittest.mock import AsyncMock, patch
@pytest.fixture
def mock_db():
db = AsyncMock()
db.users.get.return_value = {"id": 1, "name": "Test"}
return db
@pytest.mark.asyncio
async def test_get_user(mock_db):
result = await get_user(1, db=mock_db)
assert result["name"] == "Test"
mock_db.users.get.assert_called_once_with(1)
最佳实践
- 使用
ruff进行代码检查和格式化 - 使用严格模式的
mypy - 优先使用
pathlib.Path,而非os.path - 使用数据类或 Pydantic 定义数据结构
- 使用
asyncio处理 I/O 密集型操作 - 使用
contextlib.asynccontextmanager管理异步资源
评论
支持 Markdown