Skip to content

标准库全景

Python 的标准库是"内置电池"哲学的体现。掌握核心标准库,能解决 80% 的日常编程问题。

标准库分类地图

Python 标准库
├── 数据结构与算法
│   ├── collections   — 高级容器类型
│   ├── heapq         — 堆队列
│   ├── bisect        — 二分查找
│   └── array         — 高效数值数组

├── 函数式编程工具
│   ├── itertools     — 迭代器工具箱
│   ├── functools     — 高阶函数工具
│   └── operator      — 运算符函数

├── 文件与路径
│   ├── pathlib       — 面向对象路径
│   ├── os            — 操作系统接口
│   ├── shutil        — 高级文件操作
│   └── tempfile      — 临时文件

├── 数据处理
│   ├── json          — JSON 序列化
│   ├── csv           — CSV 处理
│   ├── pickle        — Python 对象序列化
│   ├── struct        — 二进制数据
│   └── re            — 正则表达式

├── 日期与时间
│   ├── datetime      — 日期时间
│   ├── time          — 时间函数
│   └── zoneinfo      — 时区(3.9+)

├── 并发
│   ├── threading     — 线程
│   ├── multiprocessing — 多进程
│   ├── concurrent.futures — 高级并发
│   └── asyncio       — 异步 I/O

├── 网络与 Web
│   ├── socket        — 底层网络
│   ├── http.client   — HTTP 客户端
│   ├── urllib        — URL 处理
│   └── email         — 邮件处理

├── 开发工具
│   ├── logging       — 日志
│   ├── unittest      — 单元测试
│   ├── doctest       — 文档测试
│   ├── pdb           — 调试器
│   ├── timeit        — 性能测量
│   └── profile/cProfile — 性能分析

└── 系统与进程
    ├── sys           — 解释器接口
    ├── os            — 操作系统
    ├── subprocess    — 子进程
    └── argparse      — 命令行解析

最值得深入的标准库

重要性主要用途
collections⭐⭐⭐defaultdict、Counter、deque、namedtuple
itertools⭐⭐⭐高效迭代,函数式编程
functools⭐⭐⭐lru_cache、partial、reduce
pathlib⭐⭐⭐现代路径操作,替代 os.path
dataclasses⭐⭐⭐数据类,替代手写 __init__
contextlib⭐⭐上下文管理器工具
logging⭐⭐⭐生产级日志系统
argparse⭐⭐CLI 工具开发
re⭐⭐⭐正则表达式
subprocess⭐⭐调用外部命令
asyncio⭐⭐⭐异步编程核心
typing⭐⭐⭐类型注解系统

快速参考

选择正确的数据结构

python
from collections import defaultdict, Counter, deque, OrderedDict
from heapq import heappush, heappop

# 需要默认值的字典 → defaultdict
word_count = defaultdict(int)
for word in "hello world hello".split():
    word_count[word] += 1

# 计数 → Counter
counter = Counter("hello world hello".split())
print(counter.most_common(2))  # [('hello', 2), ('world', 1)]

# 双端队列(O(1) 两端操作)→ deque
dq = deque([1, 2, 3], maxlen=5)
dq.appendleft(0)
dq.append(4)

# 优先队列 → heapq
heap = []
heappush(heap, (3, "low"))
heappush(heap, (1, "high"))
heappush(heap, (2, "medium"))
print(heappop(heap))  # (1, 'high')

路径操作现代写法

python
from pathlib import Path

# 不再用 os.path.join
config = Path.home() / ".config" / "myapp" / "config.json"
config.parent.mkdir(parents=True, exist_ok=True)

# 读写文件
if config.exists():
    data = config.read_text(encoding='utf-8')

# 遍历目录
for py_file in Path("src").rglob("*.py"):
    print(py_file.stem, py_file.suffix)

日志最佳实践

python
import logging

# 模块级 logger(推荐)
logger = logging.getLogger(__name__)

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] %(name)s: %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)

logger.debug("调试信息")
logger.info("普通信息")
logger.warning("警告")
logger.error("错误")
logger.exception("异常(自动附加 traceback)")

点击左侧菜单深入每个标准库模块 →

本站内容由 褚成志 整理编写,仅供学习参考