在 Python 中实现模块化是提升代码可维护性和复用性的关键技术,以下是分层实践总结:
模块: 单个 .py
文件
# utils.py
def format_name(name: str) -> str:
return name.strip().title()
包: 包含 __init__.py
的目录
my_package/
├── __init__.py # 包标识文件
├── utils.py # 子模块
└── models.py
my_project/
├── src/ # 核心代码
│ ├── core/ # 核心业务逻辑
│ ├── utils/ # 工具函数库
│ ├── models/ # 数据模型
│ └── api/ # 接口层代码
├── tests/ # 单元测试
├── config/ # 配置文件
│ └── settings.py
├── scripts/ # 脚本目录
│ └── setup_db.py
├── docs/ # 文档
└── requirements.txt # 依赖列表
# 正确:从模块明确导入
from src.utils.helpers import calculate_score
# 错误:避免动态路径拼接
sys.path.append("../") # 导致路径依赖混乱
方案1: 延迟导入(函数内导入)
# module_a.py
def call_b():
from module_b import func_b # 仅在需要时导入
func_b()
方案2: 依赖注入
# 显式传递依赖对象而不是隐式导入
class Service:
def __init__(self, db_connector):
self.db = db_connector
setuptools
: 构建可安装包
# setup.py
from setuptools import setup, find_packages
setup(
name="my_package",
version="0.1",
packages=find_packages(),
install_requires=["requests>=2.25"],
entry_points={
"console_scripts": ["mycli=src.cli:main"]
}
)
poetry
(现代工具): 自动包依赖管理
import importlib
module = importlib.import_module("plugins.image_processor")
plugin_class = getattr(module, "ImagePlugin")
# config/settings.py
import os
from pathlib import Path
from dotenv import load_dotenv
env_path = Path(__file__).parent / ".env"
load_dotenv(env_path) # 加载环境变量
DB_URL = os.getenv("DATABASE_URL")
models/
仅定义数据模型)。abc
定义抽象接口,模块间通过接口通信:from abc import ABC, abstractmethod
class Database(ABC):
@abstractmethod
def connect(self):
pass
# tests/test_utils.py
import pytest
from src.utils.validator import validate_email
def test_valid_email():
assert validate_email("test@example.com") is True
""" utils.formatter 模块
用于字符串格式化的工具集合
"""
def format_currency(value: float, symbol: str = "$") -> str:
"""将数值格式化为货币字符串"""
return f"{symbol}{value:,.2f}"
my_flask_app/
├── app/
│ ├── __init__.py
│ ├── routes/
│ │ ├── auth.py # 登录注册路由
│ │ └── product.py # 商品相关路由
│ ├── models/
│ │ └── user.py # 用户模型
│ ├── services/
│ │ └── payment.py # 支付服务逻辑
│ └── templates/ # 前端模板
│
├── config.py # 全局配置
├── run.py # 启动脚本
└── requirements.txt
helpers.py
这种杂物抽屉)__all__
控制导出# utils/__init__.py
__all__ = ["format_currency", "validate_email"] # 明确的公共API
# 动态发现 plugins 目录下的模块
plugin_dir = Path(__file__).parent / "plugins"
for file in plugin_dir.glob("*.py"):
module_name = file.stem
importlib.import_module(f"plugins.{module_name}")
通过合理的模块化设计,可以显著提升项目的可扩展性和团队协作效率。始终将 "高内聚、低耦合" 作为核心原则。
参与评论
手机查看
返回顶部