惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Tenable Blog
D
DataBreaches.Net
S
Secure Thoughts
B
Blog
S
Schneier on Security
Y
Y Combinator Blog
P
Proofpoint News Feed
C
Cybersecurity and Infrastructure Security Agency CISA
C
Cyber Attacks, Cyber Crime and Cyber Security
D
Darknet – Hacking Tools, Hacker News & Cyber Security
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
F
Full Disclosure
Engineering at Meta
Engineering at Meta
L
LangChain Blog
T
Threatpost
阮一峰的网络日志
阮一峰的网络日志
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
The Hacker News
The Hacker News
月光博客
月光博客
大猫的无限游戏
大猫的无限游戏
Cyberwarzone
Cyberwarzone
T
The Exploit Database - CXSecurity.com
雷峰网
雷峰网
博客园 - 司徒正美
Help Net Security
Help Net Security
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Application and Cybersecurity Blog
Application and Cybersecurity Blog
P
Privacy International News Feed
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
V
Vulnerabilities – Threatpost
Cisco Talos Blog
Cisco Talos Blog
L
LINUX DO - 热门话题
酷 壳 – CoolShell
酷 壳 – CoolShell
T
Threat Research - Cisco Blogs
Recent Announcements
Recent Announcements
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
H
Heimdal Security Blog
Jina AI
Jina AI
C
Cisco Blogs
Attack and Defense Labs
Attack and Defense Labs
Microsoft Security Blog
Microsoft Security Blog
L
Lohrmann on Cybersecurity
aimingoo的专栏
aimingoo的专栏
D
Docker
I
Intezer
C
Check Point Blog
Cloudbric
Cloudbric
小众软件
小众软件
V2EX - 技术
V2EX - 技术

阿尔的代码屋 | 全栈技术笔记

在 Android Termux 环境下安装 Hermes Agent 的踩坑与完美解决实践 开发日志| 阿尔的代码屋 VS Code 连接 WSL 精确每 10 分钟掉线 排坑笔记 | 阿尔的代码屋 Android 模拟器代理联网与 No Internet WiFi 锁死排坑笔记 | 阿尔的代码屋 [object Object] typing_extensions 有用(四):使用 TypeIs 替代危险的 cast,做最严谨的类型收窄 | 阿尔的代码屋 GoRouter 结合 Isar 运行 Widget 测试并发/粘性线程死锁卡死排坑笔记 | 阿尔的代码屋 typing_extensions 有用(二):使用 @override 打造重构代码时的“防呆神器” | 阿尔的代码屋 Flutter 并发测试踩坑实录 - IsarCore 动态库下载冲突与 Widget 测试 HTTP 拦截全链路解决 | 阿尔的代码屋 typing_extensions 有用(一):使用 Self 终结继承时的类型推断灾难 | 阿尔的代码屋 基于 Cloudflare Pages 的纯前端 WebAssembly 应用自动化部署实践 | 开发日志 | 阿尔的代码屋 基于 VS Code 远程开发的 GPU Docker 容器自动清理方案实践 开发日志| 阿尔的代码屋 Patrol iOS 集成测试排坑实录 - xcodebuild exit code 70 全链路解决 | 阿尔的代码屋 Flutter E2E 测试从 integration_test 迁移到 Patrol - 实践笔记 | 阿尔的代码屋 Linux/macOS 下 micromamba 报错 Shard Index not available 与极度卡顿 排坑笔记 | 阿尔的代码屋 critical libmamba Shell not initialized micromamba报错 subprocess 无法修改父 Shell - 排坑笔记 | 阿尔的代码屋 VS Code Remote-SSH: 彻底告别重复输入密码 - 排坑笔记 | 阿尔的代码屋 Git 报警: inexact rename detection was skipped - 排坑笔记 | 阿尔的代码屋 解决群晖 NAS SSL 证书自动部署难题 | 阿尔的代码屋 Windows 下 Git error: fatal: refusing to work with credential missing host field - 排坑笔记 | 阿尔的代码屋 VS Code 调试 Python 第三方库源码的配置 - 开发技巧| 阿尔的代码屋 VS Code Remote Tunnels本地连接调试Kaggle GPU - 开发技巧| 阿尔的代码屋 Windows下Git error: open(xxxx) Filename too long - 排坑笔记 | 阿尔的代码屋 记录2026年零预约港卡开户实录避坑 告别孤岛:拥抱 MCP 协议,为大模型打造标准“USB 接口” - 大模型实战 08 完结篇 | 阿尔的代码屋 从 ReAct 到 Workflow:基于云端 API 构建事件驱动的智能体 - 大模型实战 07 额外篇 | 阿尔的代码屋 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent - 大模型实战 07 | 阿尔的代码屋 在 Kaggle 上用 Unsloth 极速微调 Qwen3 - 大模型实战 06 | 阿尔的代码屋 大模型微调实战详解 - 大模型实战 05 | 阿尔的代码屋 基于 ChromaDB 打造工程级 RAG 系统 - 大模型实战 04 | 阿尔的代码屋 拆解 Transformers 原理与图解 - 大模型实战 03 | 阿尔的代码屋 云端炼丹房 2:Kaggle 上手指南 - 大模型实战 03预备 | 阿尔的代码屋 云端炼丹房:Google Colab 免费 GPU 上手指南 - 大模型实战 03预备 | 阿尔的代码屋 Open WebUI 部署与 RAG 实战 - 大模型实战 02 | 阿尔的代码屋
typing_extensions 有用(三):使用 Unpack 结合 TypedDict 给 **kwargs 装上透视眼 | 阿尔的代码屋
Algieba · 2026-06-19 · via 阿尔的代码屋 | 全栈技术笔记

核心摘要 (TL;DR)

  • 背景:封装底层函数或第三方 API 时,我们经常使用 **kwargs 来接收大量可选参数,但这会导致调用者在写代码时失去任何 IDE 提示,只能靠猜或翻看源码。
  • 核心问题**kwargs 是静态类型检查的“黑洞”。
  • 关键解法:使用 TypedDict 定义严格的字典结构说明书,然后用 Unpack 将这份说明书“解包”塞进 **kwargs 中。
  • 最佳实践:抛弃旧时代的 total=False,全面拥抱 RequiredNotRequired 实现字段级的精准控制。

问题概览卡片

基本信息

  • 应用场景:编写需要接收大量可选配置项的函数(如大模型调用、数据库查询封装、绘图库配置)。
  • 技术栈:Python 3.11+ 或 typing_extensions
  • 核心痛点:极其糟糕的 API 调用体验(无补全、无类型校验)。

案发现场:让人抓狂的类型黑洞

在 Python 中,**kwargs 是个极其灵活的设计。假设我们正在封装一个大模型调用的 API:

原始代码(痛点展示):

1
2
3
4
5
6
7
8
9
def invoke_llm(prompt: str, **kwargs) -> str:

pass





invoke_llm("你好", temperture=0.9, maxTokens="100")

在讲 Unpack 之前,我们必须先打造一份“参数说明书”,这就是 TypedDict 的使命。它能在不改变字典本质(零运行时开销)的前提下,告诉 IDE 这个字典里应该长什么样。

为了应对配置项通常只有少部分是必填的场景,工业界目前最推荐的写法是结合 NotRequired

1
2
3
4
5
6
7
8
from typing_extensions import TypedDict, NotRequired, Required


class LLMKwargs(TypedDict):
model: str
temperature: NotRequired[float]
max_tokens: NotRequired[int]
stop_words: NotRequired[list[str]]

(注:在早期的 Python 版本中,人们通常使用 class LLMKwargs(TypedDict, total=False): 来让整个字典变成选填,但这种“一刀切”的方式远不如 NotRequired 精准。)


2. 核心武器二:Unpack (透视魔法)

有了说明书,接下来就是见证奇迹的时刻。我们需要用 UnpackLLMKwargs 的规则“解包”并注入到那个无法无天的 **kwargs 肚子里。

1
2
3
4
5
6
7
from typing_extensions import Unpack


def invoke_llm(prompt: str, **kwargs: Unpack[LLMKwargs]) -> str:
print(f"发送 Prompt: {prompt}")
print(f"携带参数: {kwargs}")
return "success"

体验降维打击般的开发手感

当你的同事现在去调用这个函数时,他将获得接近强类型语言的完美体验:

  1. 极其智能的代码补全:敲下 invoke_llm("hello", ) 时,IDE 自动弹出 model, temperature, max_tokens 供其选择。
  2. 严格的必填项校验:如果他没有传 model,IDE 直接画红线警告。
  3. 精准的类型拦截:如果他写了 temperature="高"(传了字符串),IDE 会立刻标红报错,防患于未然。

3. 灵魂拷问:为什么不用 Pydantic?

很多熟悉 FastAPI 或高级类型操作的开发者会问:既然都要校验数据,我为什么不直接定义一个 Pydantic 的 BaseModel 传进去?

1
2
3
4
5
6

def invoke_llm_pydantic(prompt: str, config: LLMConfigModel):
pass


invoke_llm_pydantic("hello", LLMConfigModel(model="gpt-4", temperature=0.7))

答案是:它们根本不在一个赛道竞争。

  • Pydantic 是一座“运行时的安检门”。它在代码运行时会强行校验数据、转换类型,有明显的性能开销。适合放在系统的边缘(如 HTTP 请求入口、解析不可靠的大模型 JSON 输出)来清洗脏数据。
  • TypedDict + Unpack 是“IDE 里的隐形图纸”。它保留了 Python 最传统、最优雅的 **kwargs 关键字传参习惯,同时在零运行时开销的前提下,为开发者提供了顶级的编写体验。适合用在系统内部高频流转的函数调用中。

4. 最终总结

传参方式IDE 补全静态类型检查运行时开销语法优雅度
**传统 **kwargs**❌ 无❌ 无🟢 极低🟢 极佳
Pydantic Model✅ 完美✅ 完美🔴 较高🟡 一般(需实例化)
Unpack[TypedDict]✅ 完美✅ 完美🟢 极低🟢 极佳

拥抱 Unpack,让你的框架和组件既有动态语言的飘逸,又有静态语言的严谨!