恒美微站
首页
关于我们
建站服务
主题模板
案例展示
资讯中心
联系我们
HoRain云--Python代码质量与重构:Ruff、mypy与设计原则
首页
资讯中心
/
HoRain云--Python代码质量与重构:Ruff、mypy与设计原则
HoRain云--Python代码质量与重构:Ruff、mypy与设计原则
发布时间:2026/10/14 3:27:56
代码质量决定项目寿命。本文讲解Python代码检查工具Ruff、mypy、black和重构技巧帮助你写出可维护的代码。一、Ruff极速LinterRuff用Rust编写比flake8快10-100倍集成多个工具。bash复制下载pip install ruff ruff check . ruff check --fix . ruff format .pyproject.tomltoml复制下载[tool.ruff] line-length 100 target-version py311 [tool.ruff.lint] select [E, F, W, I, N, UP, B, C4, SIM] ignore [E501] [tool.ruff.lint.isort] known-first-party [myapp]二、Black与isortbash复制下载pip install black isort black . isort .现在Ruff已能替代两者。三、mypy类型检查bash复制下载pip install mypy mypy app/python复制下载def greet(name: str) - str: return fHello, {name} greet(123) # mypy报错mypy.iniini复制下载[mypy] python_version 3.11 warn_return_any True warn_unused_configs True disallow_untyped_defs True ignore_missing_imports True四、常见代码坏味道4.1 过长函数python复制下载# 坏 def process_order(order): # 校验 if not order.items: raise ValueError() # 计算 total sum(i.price * i.qty for i in order.items) # 折扣 if order.coupon: total * 0.9 # 保存 db.save(order) # 通知 send_email(order.user) return total # 好 def validate_order(order): ... def calculate_total(order): ... def apply_coupon(order, total): ... def save_order(order): ... def notify_user(order): ... def process_order(order): validate_order(order) total calculate_total(order) total apply_coupon(order, total) save_order(order) notify_user(order) return total4.2 重复代码提取公共函数或使用继承/组合。4.3 魔法数字python复制下载# 坏 if user.age 18: ... # 好 ADULT_AGE 18 if user.age ADULT_AGE: ...4.4 过深嵌套python复制下载# 坏 def process(data): if data: if data.valid: if data.items: for item in data.items: if item.active: handle(item) # 好卫语句 def process(data): if not data or not data.valid or not data.items: return for item in data.items: if item.active: handle(item)五、SOLID原则S单一职责O开闭原则L里氏替换I接口隔离D依赖倒置python复制下载# 依赖倒置 class Notifier(Protocol): def send(self, msg: str) - None: ... class EmailNotifier: def send(self, msg: str) - None: ... class OrderService: def __init__(self, notifier: Notifier): self.notifier notifier六、重构技巧6.1 提取变量python复制下载# 坏 if user.age 18 and user.city Beijing and user.active: ... # 好 is_adult user.age 18 is_beijing user.city Beijing if is_adult and is_beijing and user.active: ...6.2 用多态替代条件python复制下载# 坏 def area(shape): if shape.type circle: return 3.14 * shape.r ** 2 elif shape.type rect: return shape.w * shape.h # 好 class Circle: def area(self): return 3.14 * self.r ** 2 class Rect: def area(self): return self.w * self.h6.3 用dataclass替代样板类python复制下载from dataclasses import dataclass dataclass class User: id: int name: str age: int 0七、CI集成yaml复制下载name: Quality on: [push] jobs: lint: runs-on: ubuntu-latest steps: - uses: actions/checkoutv3 - uses: actions/setup-pythonv4 with: python-version: 3.11 - run: pip install ruff mypy pytest - run: ruff check . - run: mypy app/ - run: pytest八、pre-commit钩子yaml复制下载# .pre-commit-config.yaml repos: - repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.1.0 hooks: - id: ruff args: [--fix] - id: ruff-format - repo: https://github.com/pre-commit/mirrors-mypy rev: v1.5.0 hooks: - id: mypybash复制下载pip install pre-commit pre-commit install九、总结代码质量是长期投资。用Ruff统一风格mypy保证类型安全遵循SOLID原则持续重构才能让项目保持活力。工具自动化检查让团队专注于业务逻辑。