Python 常见规范与高阶模式
以下文档汇总了 Python 中常用的命名规范、函数签名约定、装饰器、类型注解、魔法方法,以及在大型项目中常见的架构和操作模式。
1. 命名规范(Naming Conventions)
前缀/形式 | 含义 | 示例 |
---|---|---|
age | 普通变量/属性 | age = 30 |
_age | 单下划线:弱“私有”标记,不建议外部使用 | self._age = 30 |
__age | 双下划线:名称改写(name mangling) | self.__age = 30 |
__age__ | 双前后下划线:系统保留(魔法方法/特殊属性) | __init__ , __str__ |
ALL_CAPS | 常量 | MAX_RETRIES = 5 |
snake_case | 下划线式,函数/变量推荐 | compute_value() |
MixedCase | 类名,首字母大写驼峰式 | class MyClass: |
mixedCase | 驼峰式,不推荐,少见 | someVar |
module_name | 文件或包名,均使用小写+下划线 | utils/helpers.py |
额外补充:
__slots__
:定义在类中,限制实例属性集合。- 模块级 dunder:
__name__
,__all__
,__version__
。
2. 函数签名与参数约定
def func(pos1, pos2, /, arg1, arg2=42, *args, kw_only1, kw_only2=None, **kwargs) -> ReturnType:
...
/
前参数只能通过位置传递(Python 3.8+)。- 默认参数带默认值。
*args
:可变位置参数收集为元组。kw_only
:在*
后的参数必须通过关键字传递。**kwargs
:可变关键字参数收集为字典。-> ReturnType
:返回值类型注解。
额外补充:
- 参数前置星号:
def f(*, a, b):
强制a
、b
为关键字。 - 参数后置斜杠:
def f(a, b, /, c):
强制a
、b
为位置。 - 默认值宜使用不可变类型,避免共享可变默认值陷阱。
- 使用
typing
模块:List[int]
,Dict[str, Any]
,Optional[T]
。
3. 装饰器(Decorators)
-
@decorator
:在函数/类定义时应用,等价于:func = decorator(func)
-
内置常用装饰器:
@staticmethod
@classmethod
@property
@functools.lru_cache
-
自定义装饰器:接收被装饰对象并返回新对象。可用于权限校验、缓存、日志等场景。
额外补充:
- 带参装饰器:
def deco(arg): ...
返回实际装饰器。 functools.wraps
:保持原函数元数据。
4. 类型注解(Type Hints)
from typing import List, Dict, Optional, Union, Any
def greet(name: str, times: int = 1) -> None:
...
def parse(data: bytes) -> Union[Dict[str, Any], None]:
...
- Python 3.9+ 可直接写
list[int]
,dict[str, float]
。 # type: ignore
用于忽略特定行的类型检查。TypeVar
,Generic
用于定义泛型类。
5. 魔法方法与协议(Special Methods & Protocols)
-
常见魔法方法:
- 构造与表示:
__init__
,__new__
,__repr__
,__str__
- 容器行为:
__len__
,__getitem__
,__setitem__
,__contains__
- 可调用与迭代:
__call__
,__iter__
,__next__
- 运算符重载:
__add__
,__eq__
,__lt__
等 - 上下文管理:
__enter__
,__exit__
- 构造与表示:
-
协议(Protocol):结构化子类型,只要实现签名即可视为该类型。
额外补充:
- 自定义上下文管理器:支持
with
语句。 - 自定义迭代器:实现
__iter__
与__next__
。
6. 代码组织与项目结构
my_project/
├── src/ # 源码目录
│ └── my_package/
│ ├── __init__.py
│ ├── core.py
│ └── utils.py
├── tests/ # 单元测试
│ └── test_core.py
├── docs/ # 文档(Sphinx / MkDocs)
├── configs/ # 配置文件(yaml/json)
├── requirements.txt
├── pyproject.toml # Poetry / PEP 517
└── .github/workflows/ # CI 配置
额外补充:
- 分层:
api/
,service/
,repository/
,models/
。 - 包含
__all__
控制from module import *
。
7. 大型项目常用操作模式
- 日志记录(Logging):
logging.getLogger(__name__)
+ 配置Handler
。 - 配置管理:
pydantic
,dataclasses
, 环境变量加载。 - 测试:
pytest
+ fixtures +mock
。 - 静态检查:
mypy
,flake8
,isort
,black
。 - 依赖管理:
poetry
,pipenv
。 - CI/CD:GitHub Actions / GitLab CI。
- 文档生成:
Sphinx
+autodoc
/MkDocs
。 - 数据库/ORM:
SQLAlchemy
,Django ORM
,asyncpg
。 - 异步编程:
asyncio
,aiohttp
,FastAPI
。 - 缓存:
redis
,memcached
。 - 任务队列:
Celery
,RQ
。 - 监控:
Prometheus
,Sentry
。 - 打包分发:
setuptools
,twine
。
如有更多场景(如元类、AST 操作、性能调优、C 扩展等)可继续补充。