Appearance
Python 良好编码规范实践
1. 命名规范
python
# 模块名:小写+下划线
my_module.py
# 类名:大驼峰
class MyClass:
pass
# 函数/变量名:小写+下划线
def calculate_sum():
my_variable = 10
# 常量:全大写+下划线
MAX_SIZE = 1002. 代码布局
python
# 缩进:4个空格(不用Tab)
def function():
if condition:
do_something()
# 每行不超过 79-100 字符
# 长表达式可以换行
result = (some_long_variable + another_variable
+ yet_another_variable)
# 函数/类之间空两行
class FirstClass:
pass
class SecondClass:
pass3. 导入规范
python
# 标准库、第三方库、本地模块分组,每组间空一行
import os
import sys
import numpy as np
import pandas as pd
from my_module import my_function4. 注释和文档字符串
python
def calculate_average(numbers):
"""
计算数字列表的平均值
Args:
numbers (list): 数字列表
Returns:
float: 平均值
Raises:
ValueError: 如果列表为空
"""
if not numbers:
raise ValueError("列表不能为空")
return sum(numbers) / len(numbers)5. Python 特有的最佳实践
python
# 使用列表推导式
squares = [x**2 for x in range(10)]
# 使用 with 语句处理文件
with open('file.txt', 'r') as f:
content = f.read()
# 使用 enumerate 而非 range(len())
for i, value in enumerate(my_list):
print(f"{i}: {value}")
# 使用 .get() 安全访问字典
value = my_dict.get('key', default_value)
# 使用 is 比较 None
if variable is None:
pass6. 类型注解(推荐)
python
def greet(name: str) -> str:
return f"Hello, {name}!"
from typing import List, Dict, Optional
def process_data(items: List[int]) -> Optional[Dict[str, int]]:
if not items:
return None
return {"count": len(items), "sum": sum(items)}7. 工具推荐
- pylint / flake8:代码检查工具
- black:自动格式化工具
- mypy:类型检查工具
- isort:自动排序导入语句