Python项目结构最佳实践
📑 文章目录
一、为什么项目结构很重要?
良好的项目结构可以:
- 提高代码可读性和可维护性
- 便于团队协作和分工
- 简化测试和调试流程
- 方便打包和发布
💡 核心原则
"Flat is better than nested" - 保持简单,避免过度设计
二、推荐的项目结构
2.1 简单项目结构
my_project/
├── my_project/ # 主包目录
│ ├── __init__.py # 包初始化
│ ├── main.py # 程序入口
│ ├── module1.py # 功能模块1
│ └── module2.py # 功能模块2
├── tests/ # 测试目录
│ └── test_*.py
├── docs/ # 文档目录
├── config.yaml # 配置文件
├── requirements.txt # 依赖列表
├── .gitignore
└── README.md
2.2 复杂项目结构
complex_project/
├── src/ # 源代码根目录
│ ├── __init__.py
│ ├── core/ # 核心逻辑
│ │ ├── __init__.py
│ │ ├── models.py
│ │ └── services.py
│ ├── api/ # API层
│ │ ├── __init__.py
│ │ ├── routes.py
│ │ └── schemas.py
│ ├── utils/ # 工具函数
│ │ ├── __init__.py
│ │ └── helpers.py
│ └── config.py # 配置
├── tests/ # 测试
│ ├── unit/
│ └── integration/
├── scripts/ # 脚本
├── notebooks/ # Jupyter
├── docs/ # 文档
├── .env # 环境变量
├── .gitignore
├── requirements.txt
├── setup.py
└── README.md
三、关键文件说明
3.1 requirements.txt
# 格式:包名==版本号
numpy==1.24.0
pandas==1.5.3
requests==2.28.0
scikit-learn==1.2.0
# 或使用宽松版本
numpy>=1.20
pandas>=1.3
3.2 setup.py / pyproject.toml
# pyproject.toml (推荐)
[project]
name = "my-project"
version = "1.0.0"
description = "A short description"
requires-python = ">=3.8"
dependencies = [
"numpy>=1.20",
"pandas>=1.3",
]
[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"
3.3 .gitignore
__pycache__/
*.py[cod]
*.so
.Python
venv/
.env
*.egg-info/
dist/
build/
.coverage
.pytest_cache/
*.log
四、模块化开发要点
⚠️ 注意事项
- 避免循环导入(circular import)
- 使用相对导入
- 保持模块职责单一
- 编写清晰的模块文档字符串
# good_package/
# ├── __init__.py
# ├── user/
# │ ├── __init__.py
# │ ├── models.py
# │ ├── services.py
# │ └── schemas.py
# └── utils/
# ├── __init__.py
# └── helpers.py
# 从同一包导入
from .models import User
from ..utils.helpers import validate