Python 最佳实践
编写 idiomatic, clean Python: PEP 8, naming, 项目结构, tooling, and 常见约定.
你将学到
- Follow PEP 8 样式指南
- 编写 Pythonic, idiomatic code
- 结构项目 professionally
- Use linters and formatters (black, ruff)
- Apply 常见 Python 约定 and idioms
概念讲解
PEP 8 — The Style Guide
PEP 8 is Python's official style guide. Following it makes your code consistent with the entire Python ecosystem. Key rules:
Naming conventions:
snake_case— variables and functions:user_count,calculate_totalUPPER_SNAKE_CASE— constants:MAX_RETRIES,DEFAULT_TIMEOUTPascalCase— classes:MyClass,HttpRequestsnake_case— modules and packages:string_utils,file_handler_private— internal names (convention):_helper_function__dunder__— special methods:__init__,__str__
Formatting:
- 4 spaces per indentation level (never tabs)
- Maximum line length: 79 characters (or 99 for teams that agree)
- Blank lines: 2 between top-level definitions, 1 between methods
- Imports on separate lines
# Good
import os
import sys
# Bad
import os, sys
Import Order
PEP 8 recommends grouping imports in this order:
# 1. Standard library
import os
import sys
from datetime import datetime
# 2. Third-party packages
import requests
import numpy as np
# 3. Local application/modules
from myapp.models import User
from myapp.utils import format_date
Separate each group with a blank line. Sort alphabetically within each group.
Writing Pythonic Code
Pythonic means using Python's idioms and conventions naturally. Compare:
# Unpythonic — C/Java style
numbers = [1, 2, 3, 4, 5]
total = 0
for i in range(len(numbers)):
total += numbers[i]
# Pythonic — use built-in sum
total = sum(numbers)
# Unpythonic — manual index
for i in range(len(fruits)):
print(fruits[i])
# Pythonic — iterate directly
for fruit in fruits:
print(fruit)
# Unpythonic — manual index tracking
index = 0
for fruit in fruits:
print(index, fruit)
index += 1
# Pythonic — use enumerate
for index, fruit in enumerate(fruits):
print(index, fruit)
The Zen of Python
Run 导入这个 in Python to see 20 guiding principles. The most important:
- Beautiful is better than ugly
- Explicit is better than implicit
- Simple is better than complex
- Readability counts
- There should be one obvious way to do it
These principles guide every design decision in Python. When in doubt, choose the simpler, more readable solution.
Common Idioms
# Check for empty collections — use truthiness, not len()
if my_list: # good — non-empty
...
if not my_string: # good — empty string
...
# Swap variables
a, b = b, a
# Multiple assignment
x = y = z = 0
# Unpacking
first, *rest = my_list
# Default dict values
name = user.get("name", "Anonymous")
# Ternary expression
status = "adult" if age >= 18 else "minor"
# Chained comparisons
if 0 <= score <= 100: # instead of 0 <= score and score <= 100
...
# String joining (not + concatenation in loops)
result = ", ".join(words) # efficient
Project Structure
A professional Python project:
myproject/
├── pyproject.toml # project config (modern standard)
├── README.md # documentation
├── .gitignore
├── src/
│ └── myproject/
│ ├── __init__.py
│ ├── cli.py # entry point
│ ├── core.py # main logic
│ └── utils.py # helpers
├── tests/
│ ├── test_core.py
│ └── conftest.py
└── docs/
└── ...
The src/ layout prevents accidental imports from the working directory. pyproject.toml replaces 设置.py for modern projects.
Tooling
black — Code Formatter
pip install black
black my_script.py # format in place
black formats your code automatically — no debates about style. It is opinionated and uncompromising, which eliminates bikeshedding. Just run it and move on.
ruff — Fast Linter
pip install ruff
ruff check my_script.py # lint
ruff check --fix . # lint and auto-fix
ruff is an extremely fast linter (written in Rust) that replaces flake8, isort, and many other tools. It catches style violations and common bugs.
mypy — Type Checker
pip install mypy
mypy my_script.py
mypy checks type hints statically, catching type errors before runtime.
The Modern Toolchain
# Format
black .
# Lint and fix
ruff check --fix .
# Type check
mypy src/
# Test
pytest
Set up these tools to run automatically on save (via your editor) and in CI. They catch problems early and enforce consistency.
Documentation
def calculate_bmi(weight: float, height: float) -> float:
"""Calculate Body Mass Index.
The BMI is defined as weight in kilograms divided by
the square of height in meters.
Args:
weight: Weight in kilograms (must be positive).
height: Height in meters (must be positive).
Returns:
The BMI value.
Raises:
ValueError: If weight or height is not positive.
Example:
>>> calculate_bmi(70, 1.75)
22.857...
"""
if weight <= 0 or height <= 0:
raise ValueError("权重 and 高度必须是 正")
return weight / (height ** 2)
Good docstrings explain:
- What the function does (one line)
- Why (if not obvious)
- Parameters and their expected types
- Return value
- Exceptions that might be raised
- Examples (doctests)
Key Principles
- Readability over cleverness — code is read more than it is written
- Explicit is better than implicit — do not hide behavior
- One responsibility per function — small, focused functions
- Fail fast — validate inputs early, raise clear errors
- DRY but not over-abstracted — avoid premature abstraction
- Test your code — untested code is broken code
- Use the standard library — do not reinvent the wheel
- Follow PEP 8 — consistency with the ecosystem
示例代码
# --- PEP 8 compliant code ---
# Constants in UPPER_SNAKE_CASE
MAX_RETRIES = 3
DEFAULT_TIMEOUT = 30
# Imports: standard, third-party, local (with blank lines between)
import os
import sys
from datetime import datetime
import requests
from myapp.utils import format_date
# Classes in PascalCase
class User:
"""Represents a user in the system."""
def __init__(self, name: str, age: int):
self.name = name
self.age = age
def __repr__(self) -> str:
return f"User(name={self.name!r}, age={self.age})"
# Functions in snake_case with type hints and docstrings
def calculate_average(numbers: list[float]) -> float:
"""Calculate the arithmetic mean of a list of numbers.
Args:
numbers: A non-empty list of numbers.
Returns:
The arithmetic mean.
Raises:
ValueError: If the list is empty.
"""
if not numbers:
raise ValueError("Cannot calculate average of empty list")
return sum(numbers) / len(numbers)
# Pythonic idioms
def demonstrate_idioms():
fruits = ["apple", "banana", "cherry"]
# Enumerate instead of manual index
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# Truthiness check instead of len()
if fruits:
print(f"First fruit: {fruits[0]}")
# Ternary expression
count = len(fruits)
label = "fruit" if count == 1 else "fruits"
print(f"{count} {label}")
# Dict comprehension
lengths = {f: len(f) for f in fruits}
print(f"Lengths: {lengths}")
# Join instead of concatenation
print(", ".join(fruits))
# Context manager for resource management
def read_config(filename: str) -> dict:
"""Read a configuration file safely."""
with open(filename, encoding="utf-8") as f:
import json
return json.load(f)
# Main guard
if __name__ == "__main__":
demonstrate_idioms()
print(f"Average: {calculate_average([1.0, 2.0, 3.0, 4.0])}")
Shows PEP 8 compliant code: constants, 导入 排序, PascalCase 类, snake_case 函数 使用 类型 hints and docstring, Pythonic idioms (enumerate, truthiness, ternary, comprehension, 连接), 上下文 manager, and __name__ guard.
动手试一试
- JSON Formatter
Well-格式化 JSON follows 相同 原则 as well-格式化 code.
- 情况 Converter
PEP 8 naming 约定 — convert identifiers 到 正确 情况.
常见错误
错误写法
编写 非-Pythonic code 使用 manual 索引 循环 相反 的 using enumerate or direct iteration
正确做法
Use 'for 项 in 集合' for direct iteration, 'for i, 项 in enumerate(集合)' for 索引+值, and 'for 键, 值 in dict.项()' for dicts. Avoid 范围(len(...)) — 它 是 C/Java 模式, 不 Pythonic.
错误写法
不 using formatter and linter, leading 到 inconsistent 样式 跨越 codebase
正确做法
设置 black (formatter) and ruff (linter) 到 运行 automatically on 保存. black eliminates 所有 样式 debates 通过 格式化 code deterministically. ruff catches 样式 violations and 常见 bugs. 配置 你的 editor 到 运行 它们 on 保存.
相关资源
相关速查表
- Python Cheatsheet
PEP 8 规则, idioms, and 项目 结构 引用.
练习 Python 最佳实践
2 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。