setting-up-python-projects

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Setting Up Python Projects

Python项目搭建指南

New projects start with the full safety net configured. Templates are in the repo: https://github.com/quick-brown-foxxx/coding_rules_python/tree/master/templates`.
Make sure to read repo's readme.

新项目启动时需配置完整的保障机制,模板存放在以下仓库:https://github.com/quick-brown-foxxx/coding_rules_python/tree/master/templates`
请务必阅读仓库的README文档。

Project Layout

项目目录结构

project/
├── src/appname/
│   ├── __init__.py           # __version__ = "0.1.0"
│   ├── __main__.py           # Entry point
│   ├── constants.py          # Shared constants
│   ├── core/                 # Business logic
│   │   ├── models.py         # Data types (dataclasses)
│   │   ├── manager.py        # Business operations
│   │   └── exceptions.py     # Custom exception hierarchy
│   ├── cli/                  # CLI interface
│   │   ├── commands.py       # Command implementations
│   │   ├── parser.py         # Argument parsing
│   │   └── output.py         # Formatted output helpers
│   ├── ui/                   # Qt GUI (if applicable)
│   │   ├── main_window.py
│   │   ├── dialogs/
│   │   └── widgets/
│   ├── utils/                # Stateless utilities
│   │   ├── paths.py
│   │   └── logging.py
│   ├── wrappers/             # Third-party lib wrappers
│   │   └── some_wrapper.py
│   └── stubs/                # Type stubs for untyped libs
├── tests/
│   ├── unit/
│   ├── integration/
│   ├── fixtures/
│   └── conftest.py
├── scripts/                  # Dev utilities
│   ├── bootstrap.py          # Setup script
│   └── check_type_ignore.py
├── docs/
│   ├── coding_rules.md       # Copy from rules/coding_rules.md
│   └── PHILOSOPHY.md          # Copy from PHILOSOPHY.md
├── shared/                   # Cross-cutting (logging, shortcuts)
├── AGENTS.md                 # Copy from templates/AGENTS.md, customize
├── CLAUDE.md                 # Symlink → AGENTS.md
├── pyproject.toml            # Copy from templates/pyproject.toml, customize
├── .pre-commit-config.yaml   # Copy from templates/pre-commit-config.yaml
├── .gitignore                # Copy from templates/gitignore
└── .vscode/
    ├── settings.json         # Copy from templates/vscode_settings.json
    └── extensions.json       # Copy from templates/vscode_extensions.json

project/
├── src/appname/
│   ├── __init__.py           # __version__ = "0.1.0"
│   ├── __main__.py           # 入口文件
│   ├── constants.py          # 公共常量
│   ├── core/                 # 业务逻辑
│   │   ├── models.py         # 数据类型(dataclasses)
│   │   ├── manager.py        # 业务操作
│   │   └── exceptions.py     # 自定义异常层级
│   ├── cli/                  # CLI接口
│   │   ├── commands.py       # 命令实现
│   │   ├── parser.py         # 参数解析
│   │   └── output.py         # 格式化输出工具
│   ├── ui/                   # Qt GUI(如有需要)
│   │   ├── main_window.py
│   │   ├── dialogs/
│   │   └── widgets/
│   ├── utils/                # 无状态工具函数
│   │   ├── paths.py
│   │   └── logging.py
│   ├── wrappers/             # 第三方库封装
│   │   └── some_wrapper.py
│   └── stubs/                # 无类型库的类型桩文件
├── tests/
│   ├── unit/
│   ├── integration/
│   ├── fixtures/
│   └── conftest.py
├── scripts/                  # 开发工具脚本
│   ├── bootstrap.py          # 初始化脚本
│   └── check_type_ignore.py
├── docs/
│   ├── coding_rules.md       # 从rules/coding_rules.md复制
│   └── PHILOSOPHY.md          # 从PHILOSOPHY.md复制
├── shared/                   # 跨模块通用能力(日志、快捷方法)
├── AGENTS.md                 # 从templates/AGENTS.md复制,按需自定义
├── CLAUDE.md                 # 软链接 → AGENTS.md
├── pyproject.toml            # 从templates/pyproject.toml复制,按需自定义
├── .pre-commit-config.yaml   # 从templates/pre-commit-config.yaml复制
├── .gitignore                # 从templates/gitignore复制
└── .vscode/
    ├── settings.json         # 从templates/vscode_settings.json复制
    └── extensions.json       # 从templates/vscode_extensions.json复制

Setup Checklist

搭建检查清单

  1. Create directory structure:
    mkdir -p src/APPNAME tests/unit tests/integration tests/fixtures scripts docs .vscode
  2. Copy template and reference files:
    • templates/pyproject.toml
      pyproject.toml
      (update
      [project]
      section)
    • templates/AGENTS.md
      AGENTS.md
      (fill TODO sections)
    • templates/pre-commit-config.yaml
      .pre-commit-config.yaml
    • templates/gitignore
      .gitignore
    • templates/vscode_settings.json
      .vscode/settings.json
    • templates/vscode_extensions.json
      .vscode/extensions.json
    • rules/coding_rules.md
      docs/coding_rules.md
    • PHILOSOPHY.md
      docs/PHILOSOPHY.md
    • Create symlink:
      ln -s AGENTS.md CLAUDE.md
  3. Create entry points:
    python
    # src/APPNAME/__init__.py
    __version__ = "0.1.0"
    
    # src/APPNAME/__main__.py
    import sys
    
    def main() -> int:
        if len(sys.argv) > 1:
            return cli_main()  # CLI mode
        return gui_main()      # GUI mode (if applicable)
    
    if __name__ == "__main__":
        sys.exit(main())
  4. Create initial test:
    python
    # tests/test_main.py
    from APPNAME.__main__ import main
    
    def test_main_runs(capsys: pytest.CaptureFixture[str]) -> None:
        assert main() == 0
  5. Initialize environment:
    bash
    git init
    uv sync --all-extras --group dev
    uv run pre-commit install
    uv run poe lint_full
    uv run poe test
  6. Verify everything works:
    • uv run poe app
      runs the application
    • uv run poe lint_full
      passes with 0 errors
    • uv run poe test
      passes

  1. 创建目录结构:
    mkdir -p src/APPNAME tests/unit tests/integration tests/fixtures scripts docs .vscode
  2. 复制模板和参考文件:
    • templates/pyproject.toml
      pyproject.toml
      (更新
      [project]
      配置段)
    • templates/AGENTS.md
      AGENTS.md
      (填写TODO部分)
    • templates/pre-commit-config.yaml
      .pre-commit-config.yaml
    • templates/gitignore
      .gitignore
    • templates/vscode_settings.json
      .vscode/settings.json
    • templates/vscode_extensions.json
      .vscode/extensions.json
    • rules/coding_rules.md
      docs/coding_rules.md
    • PHILOSOPHY.md
      docs/PHILOSOPHY.md
    • 创建软链接:
      ln -s AGENTS.md CLAUDE.md
  3. 创建入口文件:
    python
    # src/APPNAME/__init__.py
    __version__ = "0.1.0"
    
    # src/APPNAME/__main__.py
    import sys
    
    def main() -> int:
        if len(sys.argv) > 1:
            return cli_main()  # CLI模式
        return gui_main()      # GUI模式(如有需要)
    
    if __name__ == "__main__":
        sys.exit(main())
  4. 创建初始测试用例:
    python
    # tests/test_main.py
    from APPNAME.__main__ import main
    
    def test_main_runs(capsys: pytest.CaptureFixture[str]) -> None:
        assert main() == 0
  5. 初始化环境:
    bash
    git init
    uv sync --all-extras --group dev
    uv run pre-commit install
    uv run poe lint_full
    uv run poe test
  6. 验证所有功能正常:
    • uv run poe app
      可正常运行应用
    • uv run poe lint_full
      运行通过,无错误
    • uv run poe test
      测试全部通过

Bootstrap Script

初始化脚本

python
undefined
python
undefined

scripts/bootstrap.py

scripts/bootstrap.py

"""Set up development environment.""" import subprocess
def main() -> None: subprocess.run(["uv", "sync", "--all-extras", "--group", "dev"], check=True) subprocess.run(["uv", "run", "pre-commit", "install"], check=True) print("Development environment ready.")
if name == "main": main()

---
"""搭建开发环境。""" import subprocess
def main() -> None: subprocess.run(["uv", "sync", "--all-extras", "--group", "dev"], check=True) subprocess.run(["uv", "run", "pre-commit", "install"], check=True) print("开发环境已准备就绪。")
if name == "main": main()

---

Adapt to Tech Stack & Domain

适配技术栈与业务领域

After scaffolding, adapt everything to the specific project. The templates are a starting point, not a straitjacket.
docs/PHILOSOPHY.md
is the only ruling constant — everything else bends to fit the project's tech stack, domain, and constraints.
完成脚手架搭建后,请根据具体项目调整所有内容。模板只是起点,不是硬性约束。
docs/PHILOSOPHY.md
是唯一的恒定规则,其他所有内容都可以调整以适配项目的技术栈、业务领域和限制条件。

What to adapt

可调整内容

AreaHow to adapt
Directory layoutAdd/remove/rename directories to match the domain. Not every project needs
cli/
,
ui/
,
wrappers/
,
shared/
. A data pipeline might need
pipelines/
,
schemas/
,
extractors/
. A web service might need
routes/
,
middleware/
,
repositories/
.
DependenciesAdd domain-specific libraries. Remove unused template defaults. Research current best-in-class libraries for the domain (e.g. SQLAlchemy vs raw asyncpg, Pydantic vs attrs).
pyproject.tomlAdjust ruff rules, pytest markers, basedpyright overrides for the domain. Some domains need relaxed rules (e.g. data science may need broader
type: ignore
for numpy interop).
AGENTS.mdFill TODO sections with project-specific architecture, key decisions, domain vocabulary, and workflows. This is the agent's primary orientation document — make it specific.
coding_rules.mdExtend or override rules for the domain. Add domain-specific conventions (e.g. database migration rules, API versioning policy, data validation requirements).
Test structureAdjust to match what matters. A CLI tool needs heavy e2e tests. A library needs heavy unit tests. A web service needs API integration tests.
CI/CDAdd domain-appropriate checks (e.g. migration consistency, API schema validation, container builds).
模块调整方式
目录结构新增/删除/重命名目录以匹配业务领域,并非所有项目都需要
cli/
ui/
wrappers/
shared/
。数据 pipeline 项目可能需要
pipelines/
schemas/
extractors/
,Web服务项目可能需要
routes/
middleware/
repositories/
依赖新增业务领域相关的库,删除模板中未使用的默认依赖。调研业务领域当前最优的类库(例如SQLAlchemy vs 原生asyncpg,Pydantic vs attrs)。
pyproject.toml根据业务领域调整ruff规则、pytest标记、basedpyright覆盖配置。部分领域需要放宽规则,例如数据科学场景可能需要为numpy兼容设置更宽松的
type: ignore
规则。
AGENTS.md填写项目专属的架构设计、核心决策、业务术语和工作流到TODO部分,这是Agent的核心指引文档,请尽量具体。
coding_rules.md扩展或覆盖适配业务领域的规则,新增业务专属约定(例如数据库迁移规则、API版本策略、数据校验要求)。
测试结构根据项目核心需求调整:CLI工具需要大量端到端测试,类库需要大量单元测试,Web服务需要API集成测试。
CI/CD新增适配业务领域的检查项(例如迁移一致性检查、API schema校验、容器构建)。

Research before building

构建前调研

When setting up a project in an unfamiliar domain or with unfamiliar libraries:
  1. Research the domain's conventions — look up how well-maintained projects in the same space are structured
  2. Check library compatibility — verify libraries work together and with basedpyright strict mode (some libraries have poor type stubs; plan wrappers early)
  3. Identify domain-specific tooling — some domains have their own linters, formatters, or validation tools that complement the base toolchain
  4. Check for basedpyright known issues — some libraries (numpy, pandas, SQLAlchemy) need specific configuration or stub packages to work cleanly in strict mode
在不熟悉的业务领域或使用不熟悉的类库搭建项目时,请遵循以下步骤:
  1. 调研领域通用约定 — 参考同领域成熟维护项目的结构
  2. 检查类库兼容性 — 确认类库之间以及与basedpyright严格模式的兼容性,部分类库的类型桩文件质量较差,请提前规划封装层
  3. 识别领域专属工具 — 部分业务领域有专属的lint、格式化或校验工具,可以补充到基础工具链中
  4. 检查basedpyright已知问题 — 部分类库(numpy、pandas、SQLAlchemy)需要特定配置或桩包才能在严格模式下正常运行

Quick customization checklist

快速自定义检查清单

  • Directory layout matches the domain, not the generic template
  • Dependencies are domain-appropriate (researched, not guessed)
  • AGENTS.md describes this project, not a generic Python project
  • coding_rules.md has domain-specific additions if needed
  • Test structure reflects what matters most for this project
  • basedpyright config accounts for domain-specific library quirks
  • 目录结构匹配业务领域,而非通用模板
  • 依赖适配业务领域(经过调研,而非猜测选择)
  • AGENTS.md描述的是当前项目,而非通用Python项目
  • 如有需要,coding_rules.md已新增业务领域相关规则
  • 测试结构匹配项目核心优先级
  • basedpyright配置已适配业务领域类库的特殊要求