python-project-structure by wshobson/agents
npx skills add https://github.com/wshobson/agents --skill python-project-structure设计组织良好的 Python 项目,包含清晰的模块边界、明确的公共接口和可维护的目录结构。良好的组织使代码易于发现,变更可预测。
__all__ 定义模块的公共 API将一起变更的相关代码分组。一个模块应具有单一、明确的目的。
使用 __all__ 定义公共内容。未列出的所有内容都是内部实现细节。
优先使用浅层目录结构。仅当存在真正的子域时才增加深度。
在整个项目中统一应用命名和组织模式。
myproject/
├── src/
│ └── myproject/
│ ├── __init__.py
│ ├── services/
│ ├── models/
│ └── api/
├── tests/
├── pyproject.toml
└── README.md
每个文件应专注于一个概念或一组紧密相关的功能。在以下情况时考虑拆分文件:
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
处理多个不相关的职责
增长超过 300-500 行(根据复杂度而异)
包含因不同原因而变更的类
__all__ 定义显式公共 API为每个模块定义公共接口。未列出的成员是内部实现细节。
# mypackage/services/__init__.py
from .user_service import UserService
from .order_service import OrderService
from .exceptions import ServiceError, ValidationError
__all__ = [
"UserService",
"OrderService",
"ServiceError",
"ValidationError",
]
# 内部助手函数通过省略保持私有
# from .internal_helpers import _validate_input # 不导出
优先使用最少的嵌套。深层层级会使导入冗长且导航困难。
# 首选:扁平结构
project/
├── api/
│ ├── routes.py
│ └── middleware.py
├── services/
│ ├── user_service.py
│ └── order_service.py
├── models/
│ ├── user.py
│ └── order.py
└── utils/
└── validation.py
# 避免:深层嵌套
project/core/internal/services/impl/user/
仅当存在真正需要隔离的子域时才添加子包。
选择一种方法并在整个项目中一致地应用它。
选项 A:测试与代码放在一起
src/
├── user_service.py
├── test_user_service.py
├── order_service.py
└── test_order_service.py
优点:测试文件位于其验证的代码旁边。易于发现覆盖率缺口。
选项 B:并行测试目录
src/
├── services/
│ ├── user_service.py
│ └── order_service.py
tests/
├── services/
│ ├── test_user_service.py
│ └── test_order_service.py
优点:生产代码和测试代码清晰分离。适用于大型项目的标准做法。
使用 __init__.py 为包的使用者提供清晰的公共接口。
# mypackage/__init__.py
"""MyPackage - 一个用于处理有用事务的库。"""
from .core import MainClass, HelperClass
from .exceptions import PackageError, ConfigError
from .config import Settings
__all__ = [
"MainClass",
"HelperClass",
"PackageError",
"ConfigError",
"Settings",
]
__version__ = "1.0.0"
使用者随后可以直接从包中导入:
from mypackage import MainClass, Settings
按架构层次组织代码,以实现清晰的关注点分离。
myapp/
├── api/ # HTTP 处理器,请求/响应
│ ├── routes/
│ └── middleware/
├── services/ # 业务逻辑
├── repositories/ # 数据访问
├── models/ # 领域实体
├── schemas/ # API 模式 (Pydantic)
└── config/ # 配置
每一层应仅依赖于其下方的层,绝不依赖于上方的层。
对于复杂的应用程序,按业务领域而非技术层来组织。
ecommerce/
├── users/
│ ├── models.py
│ ├── services.py
│ ├── repository.py
│ └── api.py
├── orders/
│ ├── models.py
│ ├── services.py
│ ├── repository.py
│ └── api.py
└── shared/
├── database.py
└── exceptions.py
snake_case:user_repository.pyuser_repository.py 而非 usr_repo.pyUserService 位于 user_service.py 中为清晰和可靠,使用绝对导入:
# 首选:绝对导入
from myproject.services import UserService
from myproject.models import User
# 避免:相对导入
from ..services import UserService
from . import models
当模块被移动或重组时,相对导入可能会失效。
__all__ - 明确公共接口每周安装量
3.7K
代码仓库
GitHub 星标数
32.2K
首次出现
2026年1月30日
安全审计
安装于
opencode3.0K
gemini-cli3.0K
codex3.0K
github-copilot2.7K
cursor2.6K
claude-code2.6K
Design well-organized Python projects with clear module boundaries, explicit public interfaces, and maintainable directory structures. Good organization makes code discoverable and changes predictable.
__all__Group related code that changes together. A module should have a single, clear purpose.
Define what's public with __all__. Everything not listed is an internal implementation detail.
Prefer shallow directory structures. Add depth only for genuine sub-domains.
Apply naming and organization patterns uniformly across the project.
myproject/
├── src/
│ └── myproject/
│ ├── __init__.py
│ ├── services/
│ ├── models/
│ └── api/
├── tests/
├── pyproject.toml
└── README.md
Each file should focus on a single concept or closely related set of functions. Consider splitting when a file:
Handles multiple unrelated responsibilities
Grows beyond 300-500 lines (varies by complexity)
Contains classes that change for different reasons
__all__Define the public interface for every module. Unlisted members are internal implementation details.
# mypackage/services/__init__.py
from .user_service import UserService
from .order_service import OrderService
from .exceptions import ServiceError, ValidationError
__all__ = [
"UserService",
"OrderService",
"ServiceError",
"ValidationError",
]
# Internal helpers remain private by omission
# from .internal_helpers import _validate_input # Not exported
Prefer minimal nesting. Deep hierarchies make imports verbose and navigation difficult.
# Preferred: Flat structure
project/
├── api/
│ ├── routes.py
│ └── middleware.py
├── services/
│ ├── user_service.py
│ └── order_service.py
├── models/
│ ├── user.py
│ └── order.py
└── utils/
└── validation.py
# Avoid: Deep nesting
project/core/internal/services/impl/user/
Add sub-packages only when there's a genuine sub-domain requiring isolation.
Choose one approach and apply it consistently throughout the project.
Option A: Colocated Tests
src/
├── user_service.py
├── test_user_service.py
├── order_service.py
└── test_order_service.py
Benefits: Tests live next to the code they verify. Easy to see coverage gaps.
Option B: Parallel Test Directory
src/
├── services/
│ ├── user_service.py
│ └── order_service.py
tests/
├── services/
│ ├── test_user_service.py
│ └── test_order_service.py
Benefits: Clean separation between production and test code. Standard for larger projects.
Use __init__.py to provide a clean public interface for package consumers.
# mypackage/__init__.py
"""MyPackage - A library for doing useful things."""
from .core import MainClass, HelperClass
from .exceptions import PackageError, ConfigError
from .config import Settings
__all__ = [
"MainClass",
"HelperClass",
"PackageError",
"ConfigError",
"Settings",
]
__version__ = "1.0.0"
Consumers can then import directly from the package:
from mypackage import MainClass, Settings
Organize code by architectural layer for clear separation of concerns.
myapp/
├── api/ # HTTP handlers, request/response
│ ├── routes/
│ └── middleware/
├── services/ # Business logic
├── repositories/ # Data access
├── models/ # Domain entities
├── schemas/ # API schemas (Pydantic)
└── config/ # Configuration
Each layer should only depend on layers below it, never above.
For complex applications, organize by business domain rather than technical layer.
ecommerce/
├── users/
│ ├── models.py
│ ├── services.py
│ ├── repository.py
│ └── api.py
├── orders/
│ ├── models.py
│ ├── services.py
│ ├── repository.py
│ └── api.py
└── shared/
├── database.py
└── exceptions.py
snake_case for all file and module names: user_repository.pyuser_repository.py not usr_repo.pyUserService in user_service.pyUse absolute imports for clarity and reliability:
# Preferred: Absolute imports
from myproject.services import UserService
from myproject.models import User
# Avoid: Relative imports
from ..services import UserService
from . import models
Relative imports can break when modules are moved or reorganized.
__all__ explicitly - Make public interfaces clearWeekly Installs
3.7K
Repository
GitHub Stars
32.2K
First Seen
Jan 30, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
opencode3.0K
gemini-cli3.0K
codex3.0K
github-copilot2.7K
cursor2.6K
claude-code2.6K
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
102,200 周安装