python-standards

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Python Standards

Python 开发规范

Modern Python with uv + ruff + mypy + pytest. All config in pyproject.toml.
基于 uv + ruff + mypy + pytest 的现代 Python 开发方式,所有配置统一在 pyproject.toml 中管理。

Toolchain

工具链

ToolPurpose
uvDependencies + virtual envs (lockfile:
uv.lock
)
ruffLinting + formatting (replaces black, isort, flake8)
mypyType checking (strict mode)
pytestTesting + coverage
bash
undefined
工具用途
uv依赖管理 + 虚拟环境(锁文件:
uv.lock
ruff代码检查 + 格式化(替代 black、isort、flake8)
mypy类型校验(严格模式)
pytest测试 + 覆盖率统计
bash
undefined

Setup

Setup

uv init && uv add <deps> && uv sync
uv init && uv add <deps> && uv sync

Daily workflow

Daily workflow

uv run ruff check . --fix && uv run ruff format . uv run mypy . && uv run pytest
undefined
uv run ruff check . --fix && uv run ruff format . uv run mypy . && uv run pytest
undefined

Type Hints

类型提示

All functions and classes must have explicit type hints:
python
def fetch_user(user_id: str) -> User | None:
    """Fetch user by ID."""
    ...

def process_items(items: list[Item]) -> dict[str, int]:
    ...
mypy strict mode:
toml
[tool.mypy]
strict = true
disallow_untyped_defs = true
disallow_any_generics = true
所有函数和类必须添加明确的类型提示:
python
def fetch_user(user_id: str) -> User | None:
    """Fetch user by ID."""
    ...

def process_items(items: list[Item]) -> dict[str, int]:
    ...
mypy 严格模式配置:
toml
[tool.mypy]
strict = true
disallow_untyped_defs = true
disallow_any_generics = true

Package Structure

包结构

Feature-based, not layer-based:
src/myproject/
  users/           # Domain
    __init__.py    # Public API: __all__ = ['User', 'UserService']
    models.py
    services.py
  orders/          # Another domain
  shared/          # Cross-cutting concerns
采用基于功能的结构,而非分层结构:
src/myproject/
  users/           # Domain
    __init__.py    # Public API: __all__ = ['User', 'UserService']
    models.py
    services.py
  orders/          # Another domain
  shared/          # Cross-cutting concerns

Error Handling

错误处理

Catch specific exceptions with context:
python
try:
    result = parse_config(path)
except FileNotFoundError:
    logger.warning(f"Config not found: {path}")
    return defaults
except json.JSONDecodeError as e:
    raise ConfigError(f"Invalid JSON in {path}") from e
Never: bare
except:
, silent swallowing,
except Exception
.
捕获特定异常并附带上下文信息:
python
try:
    result = parse_config(path)
except FileNotFoundError:
    logger.warning(f"Config not found: {path}")
    return defaults
except json.JSONDecodeError as e:
    raise ConfigError(f"Invalid JSON in {path}") from e
禁止:使用无限制的
except:
、静默忽略异常、
except Exception
捕获所有异常。

pyproject.toml

pyproject.toml 配置

Single source of truth (no setup.py, requirements.txt):
toml
[project]
name = "myproject"
version = "1.0.0"
requires-python = ">=3.11"
dependencies = ["httpx", "pydantic"]

[project.optional-dependencies]
dev = ["pytest", "mypy", "ruff"]

[tool.ruff]
select = ["E", "W", "F", "I", "B", "UP", "SIM", "S", "ANN"]
line-length = 88

[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = ["--cov=src", "--cov-fail-under=85"]
单一配置源(不再使用 setup.py、requirements.txt):
toml
[project]
name = "myproject"
version = "1.0.0"
requires-python = ">=3.11"
dependencies = ["httpx", "pydantic"]

[project.optional-dependencies]
dev = ["pytest", "mypy", "ruff"]

[tool.ruff]
select = ["E", "W", "F", "I", "B", "UP", "SIM", "S", "ANN"]
line-length = 88

[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = ["--cov=src", "--cov-fail-under=85"]

Anti-Patterns

反模式

  • Any
    without documented justification
  • Layer-based folders (
    /controllers
    ,
    /models
    ,
    /views
    )
  • Circular imports
  • Legacy tools (pip, black+isort, flake8)
  • Multiple config files
  • noqa
    comments without justification
  • 无文档说明的情况下使用
    Any
    类型
  • 采用分层文件夹结构(如
    /controllers
    /models
    /views
  • 循环导入
  • 使用旧版工具(pip、black+isort、flake8)
  • 存在多个配置文件
  • 无合理理由使用
    noqa
    注释

References

参考资料

  • testing-patterns.md - pytest, fixtures, parametrize
  • ruff-config.md - Complete ruff rule configuration
  • testing-patterns.md - pytest、fixtures、参数化测试
  • ruff-config.md - 完整的 ruff 规则配置