improving-python-code-quality

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Python Code Quality

Python代码质量

Quick Reference

快速参考

ToolPurposeCommand
ruffLint + format
ruff check src && ruff format src
mypyType check
mypy src
工具用途命令
ruff代码检查+格式化
ruff check src && ruff format src
mypy类型检查
mypy src

Ruff Configuration

Ruff配置

Minimal config in pyproject.toml:
toml
[tool.ruff]
line-length = 88
target-version = "py310"

[tool.ruff.lint]
select = ["E", "W", "F", "I", "B", "C4", "UP"]
For full configuration options, see RUFF_CONFIG.md.
pyproject.toml中的极简配置:
toml
[tool.ruff]
line-length = 88
target-version = "py310"

[tool.ruff.lint]
select = ["E", "W", "F", "I", "B", "C4", "UP"]
如需完整配置选项,请查看 RUFF_CONFIG.md

MyPy Configuration

Mypy配置

toml
[tool.mypy]
python_version = "3.10"
disallow_untyped_defs = true
warn_return_any = true
For strict settings and overrides, see MYPY_CONFIG.md.
toml
[tool.mypy]
python_version = "3.10"
disallow_untyped_defs = true
warn_return_any = true
如需严格设置和覆盖配置,请查看 MYPY_CONFIG.md

Type Hints Patterns

类型提示模式

python
undefined
python
undefined

Basic

基础用法

def process(items: list[str]) -> dict[str, int]: ...
def process(items: list[str]) -> dict[str, int]: ...

Optional

可选参数

def fetch(url: str, timeout: int | None = None) -> bytes: ...
def fetch(url: str, timeout: int | None = None) -> bytes: ...

Callable

可调用对象

def apply(func: Callable[[int], str], value: int) -> str: ...
def apply(func: Callable[[int], str], value: int) -> str: ...

Generic

泛型

T = TypeVar("T") def first(items: Sequence[T]) -> T | None: ...

For protocols and advanced patterns, see **[TYPE_PATTERNS.md](TYPE_PATTERNS.md)**.
T = TypeVar("T") def first(items: Sequence[T]) -> T | None: ...

如需了解协议和高级模式,请查看 **[TYPE_PATTERNS.md](TYPE_PATTERNS.md)**。

Common Anti-Patterns

常见反模式

python
undefined
python
undefined

Bad: Mutable default

不良写法:可变默认参数

def process(items: list = []): # Bug! ...
def process(items: list = []): # 存在Bug! ...

Good: None default

推荐写法:None作为默认值

def process(items: list | None = None): items = items or [] ...

```python
def process(items: list | None = None): items = items or [] ...

```python

Bad: Bare except

不良写法:裸except语句

try: ... except: pass
try: ... except: pass

Good: Specific exception

推荐写法:捕获特定异常

try: ... except ValueError as e: logger.error(e)
undefined
try: ... except ValueError as e: logger.error(e)
undefined

Pythonic Idioms

Pythonic编程风格

python
undefined
python
undefined

Iteration

迭代

for item in items: # Not: for i in range(len(items)) for i, item in enumerate(items): # When index needed
for item in items: # 不推荐:for i in range(len(items)) for i, item in enumerate(items): # 需要索引时使用

Dictionary access

字典访问

value = d.get(key, default) # Not: if key in d: value = d[key]
value = d.get(key, default) # 不推荐:if key in d: value = d[key]

Context managers

上下文管理器

with open(path) as f: # Not: f = open(path); try: finally: f.close()
with open(path) as f: # 不推荐:f = open(path); try: finally: f.close()

Comprehensions (simple only)

推导式(仅适用于简单场景)

squares = [x**2 for x in numbers]
undefined
squares = [x**2 for x in numbers]
undefined

Module Organization

模块组织结构

src/my_library/
├── __init__.py      # Public API exports
├── _internal.py     # Private (underscore prefix)
├── exceptions.py    # Custom exceptions
├── types.py         # Type definitions
└── py.typed         # Type hint marker
src/my_library/
├── __init__.py      # 公开API导出
├── _internal.py     # 内部模块(以下划线前缀标识)
├── exceptions.py    # 自定义异常
├── types.py         # 类型定义
└── py.typed         # 类型提示标记

Checklist

检查清单

Code Quality:
- [ ] ruff check passes
- [ ] mypy passes (strict mode)
- [ ] Public API has type hints
- [ ] Public API has docstrings
- [ ] No mutable default arguments
- [ ] Specific exception handling
- [ ] py.typed marker present
代码质量:
- [ ] ruff check 检查通过
- [ ] mypy 检查通过(严格模式)
- [ ] 公开API包含类型提示
- [ ] 公开API包含文档字符串
- [ ] 无可变默认参数
- [ ] 异常处理精准
- [ ] 存在py.typed标记

Learn More

更多参考

本技能基于Will McGinnis撰写的《高质量Python库开发指南》(Guide to Developing High-Quality Python Libraries)中的「代码质量」章节(Code Quality)。