7 Python Libraries You're Not Using But Should Be in 2025
7 Python Libraries You’re Not Using But Should Be in 2025
2025 年你应该使用但尚未使用的 7 个 Python 库
Python’s ecosystem grows every year, and 2025 has brought some incredible libraries that can dramatically simplify your workflow. While everyone knows about requests, pandas, and numpy, let me share 7 lesser-known gems that have genuinely changed how I write code. Python 的生态系统每年都在增长,2025 年带来了一些令人惊叹的库,可以极大地简化你的工作流程。虽然每个人都知道 requests、pandas 和 numpy,但请允许我分享 7 个鲜为人知的瑰宝,它们确实改变了我编写代码的方式。
1. 🐍 pydantic-core + pydantic v2 — Data Validation on Steroids
1. 🐍 pydantic-core + pydantic v2 — 强力数据验证
Most developers use Pydantic, but Pydantic v2 is a completely different beast. Written in Rust via pydantic-core, it’s 5-50x faster than v1. 大多数开发者都在使用 Pydantic,但 Pydantic v2 是一个完全不同的“野兽”。它通过 pydantic-core 使用 Rust 编写,速度比 v1 版本快 5 到 50 倍。
from pydantic import BaseModel, field_validator
from datetime import date
class Event(BaseModel):
name: str
date: date
attendees: int
@field_validator("name")
@classmethod
def name_must_not_be_empty(cls, v):
if not v.strip():
raise ValueError("Event name cannot be empty")
return v.strip()
event = Event(name=" DevConf 2025 ", date="2025-09-15", attendees=500)
print(event.name) # "DevConf 2025" — automatically stripped
Why it matters: Fast validation + automatic type coercion = fewer bugs, less boilerplate code. 为什么重要: 快速验证 + 自动类型转换 = 更少的 Bug,更少的样板代码。
2. 🌐 httpx — The Modern HTTP Client That Replaces requests
2. 🌐 httpx — 取代 requests 的现代 HTTP 客户端
If you’re still using requests for everything, httpx is the upgrade you need. 如果你还在用 requests 处理一切,httpx 就是你需要的升级版。
import httpx
import asyncio
async def fetch_api():
async with httpx.AsyncClient() as client:
resp = await client.get("https://api.github.com/users/octocat")
return resp.json()
# Works in sync too!
resp = httpx.get("https://api.github.com/users/octocat")
print(resp.json()["name"])
Why switch? Async support built-in, HTTP/2 support, timeout defaults that actually make sense, and a nearly identical API to requests. 为什么要切换? 内置异步支持、HTTP/2 支持、合理的默认超时设置,以及与 requests 几乎相同的 API。
3. 🎨 rich — Make Your CLI Apps Beautiful
3. 🎨 rich — 让你的 CLI 应用变得美观
Stop printing plain text. rich gives you colors, tables, progress bars, and syntax highlighting — all in the terminal. 别再只打印纯文本了。rich 可以为你提供颜色、表格、进度条和语法高亮——所有这些都在终端中实现。
from rich.console import Console
from rich.table import Table
from rich.progress import track
console = Console()
# Beautiful tables
table = Table(title="Server Status")
table.add_column("Server", style="cyan")
table.add_column("Status", style="green")
table.add_column("Uptime", justify="right")
table.add_row("web-01", "🟢 Running", "99.9%")
table.add_row("db-01", "🟢 Running", "99.7%")
table.add_row("cache-01", "🟡 Warning", "95.2%")
console.print(table)
# Progress bars with track()
for task in track(range(100), description="Processing..."):
pass # do work
Your scripts will look professional with almost zero extra effort. 你的脚本将看起来非常专业,且几乎不需要额外的工作量。
4. 📝 typer — Build CLI Apps in Minutes, Not Hours
4. 📝 typer — 在几分钟内构建 CLI 应用
import typer
app = typer.Typer()
@app.command()
def hello(name: str, count: int = 1):
"""Say hello multiple times."""
for _ in range(count):
typer.echo(f"Hello {name}!")
@app.command()
def goodbye(name: str):
typer.echo(f"Goodbye {name}! 👋")
if __name__ == "__main__":
app()
Auto-generated help, type validation, and completion scripts. It’s Click but actually pleasant to use. 自动生成的帮助文档、类型验证和补全脚本。它就像 Click,但用起来更令人愉悦。
5. 🔍 watchdog — Monitor File System Changes
5. 🔍 watchdog — 监控文件系统变更
Perfect for build tools, auto-reloaders, and sync scripts. 非常适合构建工具、自动重载器和同步脚本。
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import time
class MyHandler(FileSystemEventHandler):
def on_modified(self, event):
if event.src_path.endswith(".py"):
print(f"🔥 Changed: {event.src_path}")
observer = Observer()
observer.schedule(MyHandler(), path=".", recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
Build your own hot-reload system in 20 lines. 用 20 行代码构建你自己的热重载系统。
6. 📊 polars — The DataFrame Library That’s Eating Pandas’ Lunch
6. 📊 polars — 正在蚕食 Pandas 市场的 DataFrame 库
If you work with data, polars is the modern alternative to pandas that’s significantly faster and uses less memory. 如果你从事数据工作,polars 是 pandas 的现代替代品,它速度显著更快且占用内存更少。
import polars as pl
df = pl.scan_csv("large_dataset.csv") # Lazy evaluation!
result = (
df.filter(pl.col("age") > 25)
.group_by("department")
.agg([
pl.col("salary").mean().alias("avg_salary"),
pl.col("id").count().alias("count")
])
.sort("avg_salary", descending=True)
.collect() # Execute the query
)
print(result)
Lazy evaluation, multi-threaded execution, and a cleaner API. For datasets over 100K rows, the speed difference is dramatic. 惰性求值、多线程执行以及更简洁的 API。对于超过 10 万行的数据集,速度差异非常巨大。
7. ⚡ orjson — The Fastest JSON Library for Python
7. ⚡ orjson — Python 最快的 JSON 库
Drop-in replacement for the standard json module that’s 2-3x faster. 标准 json 模块的直接替代品,速度快 2-3 倍。
import orjson
# Serialize
data = {"users": [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]}
serialized = orjson.dumps(data, option=orjson.OPT_INDENT_2)
# Deserialize
parsed = orjson.loads(serialized)
Also handles datetime, UUID, and numpy types natively — no custom encoders needed. 还能原生处理 datetime、UUID 和 numpy 类型——无需自定义编码器。
Bonus: Quick Comparison Table
附录:快速对比表
| Library | Replaces | Speed Gain | Key Feature |
|---|---|---|---|
| 库 | 替代 | 速度提升 | 核心功能 |
| pydantic v2 | pydantic v1 | 5-50x | Rust-powered validation |
| httpx | requests | Async native | HTTP/2 support |
| rich | print() | N/A | Beautiful terminal output |
| typer | click/argparse | N/A | Type hints → CLI |
| watchdog | polling loops | N/A | Cross-platform file events |
| polars | pandas | 5-20x | Lazy + multi-threaded |
| orjson | json | 2-3x | Native datetime support |
Conclusion
结论
The Python ecosystem in 2025 is all about performance and developer experience. Libraries like polars and pydantic-core leverage Rust under the hood for speed, while typer and rich make your tools feel polished and professional. 2025 年的 Python 生态系统完全围绕性能和开发者体验展开。像 polars 和 pydantic-core 这样的库在底层利用 Rust 来提升速度,而 typer 和 rich 则让你的工具看起来精致且专业。
Which of these are you already using? Which one are you going to try first? Drop a comment below — I’d love to hear what’s in your toolbox! 你已经在用其中的哪些库了?你打算先尝试哪一个?在下方留言吧——我很想知道你的工具箱里都有什么!