mcpField
P
python-best-practices

python-best-practices

github.com/rohitg00开发2.8k210 次安装25 周前更新
代码仓库

关于 python-best-practices

面向 Python 开发者的最佳实践技能,涵盖类型标注、数据模型、异步代码、项目配置、测试与错误处理,并以代码示例说明常见实现选择。

主要功能

  1. 01函数类型标注与严格检查
  2. 02Dataclasses 与 Pydantic 的选择
  3. 03异步 I/O 与并发模式
  4. 04项目布局与 pyproject.toml
  5. 05pytest 测试模式
  6. 06Python 惯用写法与错误处理

适用场景

  1. 01为 Python 项目制定规范
  2. 02检查异步 HTTP 与资源管理
  3. 03选择内部及外部数据模型
  4. 04组织测试与异常处理

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/rohitg00/awesome-claude-code-toolkit --skill python-best-practices

安装后在 Claude Code 中输入/python-best-practices确认已加载。

详细介绍

Python 最佳实践

类型提示(3.12+ 语法)

# Use built-in generics (3.9+), no need for typing.List, typing.Dict
def process_items(items: list[str]) -> dict[str, int]:
    return {item: len(item) for item in items}

# Union with | syntax (3.10+)
def find_user(user_id: int) -> User | None:
    ...

# Type parameter syntax (3.12+)
type Vector[T] = list[T]
type Matrix[T] = list[Vector[T]]

def first[T](items: list[T]) -> T:
    return items[0]

# TypedDict for structured dicts
from typing import TypedDict

class UserResponse(TypedDict):
    id: int
    name: str
    email: str
    active: bool

始终为函数签名添加类型标注。在 CI 中使用 mypy --strict 或 pyright。谨慎使用 type: ignore 注释,并说明理由。

Dataclasses 与 Pydantic

Dataclasses(内部数据,无需验证)
from dataclasses import dataclass, field

@dataclass(frozen=True, slots=True)
class Point:
    x: float
    y: float

    def distance_to(self, other: "Point") -> float:
        return ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.5

@dataclass
class Config:
    host: str = "localhost"
    port: int = 8080
    tags: list[str] = field(default_factory=list)

对不可变值对象使用 frozen=True。使用 slots=True 提高内存效率。

Pydantic(外部输入,需要验证)
from pydantic import BaseModel, Field, field_validator

class CreateUserRequest(BaseModel):
    model_config = {"strict": True}

    email: str = Field(max_length=255)
    name: str = Field(min_length=1, max_length=100)
    age: int = Field(ge=13, le=150)

    @field_validator("email")
    @classmethod
    def validate_email(cls, v: str) -> str:
        if "@" not in v:
            raise ValueError("Invalid email format")
        return v.lower()

规则:领域模型和内部结构体使用 dataclasses。API 边界、配置文件和外部数据解析使用 Pydantic。

异步模式

import asyncio
import httpx

async def fetch_user(client: httpx.AsyncClient, user_id: int) -> User:
    response = await client.get(f"/users/{user_id}")
    response.raise_for_status()
    return User(**response.json())

async def fetch_all_users(user_ids: list[int]) -> list[User]:
    async with httpx.AsyncClient(base_url="https://api.example.com") as client:
        tasks = [fetch_user(client, uid) for uid in user_ids]
        return await asyncio.gather(*tasks)

async def process_with_semaphore(items: list[str], max_concurrent: int = 10):
    semaphore = asyncio.Semaphore(max_concurrent)
    async def bounded_process(item: str):
        async with semaphore:
            return await process_item(item)
    return await asyncio.gather(*[bounded_process(i) for i in items])

规则:

  • 异步 HTTP 使用 httpx,而不是 requests
  • 使用 asyncio.gather 执行并发任务,使用 asyncio.Semaphore 进行速率限制
  • 切勿在异步函数中调用阻塞式 I/O(旧代码可使用 asyncio.to_thread)
  • 使用 async with 管理资源(连接、会话)

项目结构

my-project/
  src/
    my_project/
      __init__.py
      main.py
      models.py
      services/
        __init__.py
        user_service.py
      api/
        __init__.py
        routes.py
  tests/
    conftest.py
    test_models.py
    test_services/
      test_user_service.py
  pyproject.toml

使用 src 布局,避免意外从项目根目录导入内容。

pyproject.toml

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = "my-project"
version = "1.0.0"
requires-python = ">=3.12"
dependencies = [
    "httpx>=0.27",
    "pydantic>=2.0",
]

[project.optional-dependencies]
dev = [
    "pytest>=8.0",
    "pytest-cov",
    "pytest-asyncio",
    "mypy",
    "ruff",
]

[project.scripts]
my-project = "my_project.main:cli"

[tool.ruff]
line-length = 100
target-version = "py312"

[tool.ruff.lint]
select = ["E", "F", "I", "N", "UP", "B", "SIM", "RUF"]

[tool.mypy]
strict = true

[tool.pytest.ini_options]
asyncio_mode = "auto"
testpaths = ["tests"]

使用 pyproject.toml 配置所有工具。使用 Ruff 代替 flake8 + isort + black(一个工具,速度快 10–100 倍)。

虚拟环境

# Use uv for fast dependency management
uv venv
uv pip install -e ".[dev]"

# Or standard venv
python -m venv .venv
source .venv/bin/activate
pip install -e ".[dev]"

始终使用虚拟环境。切勿全局安装包。在锁文件中固定精确版本(uv.lock 或由 pip freeze 生成的 requirements.txt)。

使用 pytest 测试

import pytest
from unittest.mock import AsyncMock, patch

@pytest.fixture
def user_service(db_session):
    return UserService(session=db_session)

async def test_create_user_returns_user_with_hashed_password(user_service):
    user = await user_service.create(email="[email protected]", password="secret")
    assert user.email == "[email protected]"
    assert user.password_hash != "secret"

async def test_create_user_rejects_duplicate_email(user_service):
    await user_service.create(email="[email protected]", password="secret")
    with pytest.raises(DuplicateEmailError):
        await user_service.create(email="[email protected]", password="other")

@pytest.fixture
def mock_http_client():
    client = AsyncMock(spec=httpx.AsyncClient)
    client.get.return_value = httpx.Response(200, json={"id": 1, "name": "Alice"})
    return client

async def test_fetch_user_parses_response(mock_http_client):
    user = await fetch_user(mock_http_client, user_id=1)
    assert user.name == "Alice"
    mock_http_client.get.assert_called_once_with("/users/1")

使用 conftest.py 存放共享 fixture。使用 pytest.mark.parametrize 测试不同情况。文件系统测试使用 tmp_path fixture。

Pythonic 惯用写法

# Unpacking
first, *rest = items
x, y = point

# Comprehensions over map/filter
squares = [x**2 for x in numbers if x > 0]
lookup = {u.id: u for u in users}

# Context managers for resource cleanup
with open(path) as f:
    data = f.read()

# Walrus operator for assign-and-test
if (match := pattern.search(text)) is not None:
    process(match.group(1))

# Structural pattern matching (3.10+)
match command:
    case {"action": "move", "direction": d}:
        move(d)
    case {"action": "quit"}:
        sys.exit(0)
    case _:
        raise ValueError(f"Unknown command: {command}")

错误处理

class AppError(Exception):
    def __init__(self, message: str, code: str):
        super().__init__(message)
        self.code = code

class NotFoundError(AppError):
    def __init__(self, resource: str, id: str):
        super().__init__(f"{resource} {id} not found", "NOT_FOUND")

# Specific exceptions, never bare except
try:
    user = await get_user(user_id)
except NotFoundError:
    return {"error": "User not found"}, 404
except DatabaseError as e:
    logger.exception("Database error fetching user")
    return {"error": "Internal error"}, 500

切勿使用裸 except:。捕获最具体的异常。使用 logger.exception() 包含回溯信息。为应用定义自定义异常层次结构。

评论

支持 Markdown