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

推荐订阅源

博客园 - Franky
W
WeLiveSecurity
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
N
News and Events Feed by Topic
Recent Commits to openclaw:main
Recent Commits to openclaw:main
S
Security Affairs
SecWiki News
SecWiki News
T
Tenable Blog
C
CERT Recently Published Vulnerability Notes
Forbes - Security
Forbes - Security
Google Online Security Blog
Google Online Security Blog
C
Cybersecurity and Infrastructure Security Agency CISA
L
LINUX DO - 热门话题
T
Threat Research - Cisco Blogs
C
Cyber Attacks, Cyber Crime and Cyber Security
Cisco Talos Blog
Cisco Talos Blog
PCI Perspectives
PCI Perspectives
Engineering at Meta
Engineering at Meta
博客园 - 聂微东
Cyberwarzone
Cyberwarzone
Hugging Face - Blog
Hugging Face - Blog
Microsoft Azure Blog
Microsoft Azure Blog
V
Vulnerabilities – Threatpost
宝玉的分享
宝玉的分享
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Vercel News
Vercel News
V
Visual Studio Blog
T
Threatpost
Project Zero
Project Zero
Know Your Adversary
Know Your Adversary
I
InfoQ
G
Google Developers Blog
博客园 - 【当耐特】
Google DeepMind News
Google DeepMind News
T
The Blog of Author Tim Ferriss
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
TaoSecurity Blog
TaoSecurity Blog
O
OpenAI News
博客园_首页
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Tor Project blog
Schneier on Security
Schneier on Security
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
博客园 - 三生石上(FineUI控件)
D
DataBreaches.Net
Security Latest
Security Latest
Attack and Defense Labs
Attack and Defense Labs
aimingoo的专栏
aimingoo的专栏
H
Heimdal Security Blog

Jiajun的技术笔记

你好,2026! TiDB 源码阅读(六):TiDB Coprocessor 源码解析 性能优化的核心思想 TiDB 源码阅读(五):索引 TiDB 源码阅读(四):AST、逻辑计划、物理计划 CockroachDB Serverless Architecture podman 无故退出 Cursor Control-L (CTRL-L) Keyboard Shortcuts in Terminal Replace docker with podman Using xmonad with xfce4 A RC script for freebsd frpc 自己动手写一个k8s controller AI 会取代你的(编程)岗位吗? 自建DERP服务器提升Tailscale连接速度(使用Nginx转发) 自动升级Docker容器 再读《程序员修炼之道-从小工到专家》 让浏览器下载文件 再读《软件随想录》/《黑客与画家》/《软技能》 HTTP 压力测试中的 Coordinated Omission 2的补码 编程语言中的 context 是什么? flutter macOS 构建出错 Flatpak 使用小记 Golang CAS 操作是怎么实现的 PostgreSQL 当MQ来使用 Clash 结合 工作VPN 的网络设计 使用 PostgreSQL 搭建 JuiceFS PostgreSQL 配置优化和日志分析 有GitHub Copilot?那就可以搭建你的ChatGPT4服务 窗口函数的使用(以PG为例) 读《为什么学生不喜欢上学》 OpenAI Prompt Engineering 摘录和总结 读《打造真正的新产品》 VueJS 总结 Linux 自动挂载 alist 提供的webdav FreeBSD 使用 vm-bhyve 安装Debian虚拟机 FreeBSD 和 Linux 网卡聚合实现提速 GPT 帮我搞定了时区转换问题 长任务系统如何处理? macOS/Linux 编译 InputLeap 使用开源软KVM - synergy-core 解决 macOS 终端hostname一直变化问题 KVM 共享 Intel 集成显卡 PromQL 备忘 读《格鲁夫给经理人的第一课》 读《打开心智》 为什么要把复杂的联表操作拆成多个单表查询? 红包系统的设计 MySQL Index Condition Pushdown Optimization Go mod 简明教程 OpenWRT 使用 Android/iOS USB 网络 搭建旁路由 Golang gRPC 错误处理 编写可维护的单元测试代码 OAuth 2 详解(六):Authorization Code Flow with PKCE OAuth 2 详解(五):Device Authorization Flow OAuth 2 详解(三):Resource Owner Password Credentials Grant OAuth 2 详解(四):Client Credentials Flow OAuth 2 详解(二):Implict Grant Flow OAuth 2 详解(一):简介及 Authorization Code 模式 ElasticSearch 学习笔记 三种git流程以及发版模型 错误处理实践 权限模型(RBAC/ABAC) OIDC(OpenID Connect) 简介 任务队列简介 PostgreSQL 操作笔记 使用Drone CI构建CI/CD系统 Golang migrate 做数据库变更管理 使用PostgreSQL做搜索引擎 Nginx 源码阅读(三): 连接池、内存池 Nginx 源码阅读(二): 请求处理 Nginx 源码阅读(一): 启动流程 Go 泛型简明教程 KVM 显卡穿透给 Windows 使用 HTTP Router 处理 Telegram Bot 按钮回调 使用反射(reflect)对结构体赋值 GIN 是如何绑定参数的 你好 2022(2021 年终总结) 用Go导入大型CSV到PostgreSQL 使用 OpenWRT 搭建软路由 使用软KVM切换器 barrier 共享键鼠 SQL 防注入及原理 使用 gomock 测试 Go 代码 gevent不是黑魔法(二): gevent 实现 gevent不是黑魔法(一): greenlet 实现 用 entgo 替代 gorm 应用内使用crontab不是那么方便 单测时要不要 mock 数据库? Sentry 自建指南 用selenium完成自动化任务 用闲置的安卓手机做垃圾电话短信过滤 推荐三个时间管理工具 一次事故反思 当JS遇到uint64:JS整数溢出问题 SQLite3 存储以及ACID原理 Redis源码阅读:pub/sub实现 Redis源码阅读:zset实现 Redis源码阅读:bitmap 位图的运算 Redis源码阅读:set是怎么做交并集运算的?
Python的yield关键字有什么作用?
2016-11-29 · via Jiajun的技术笔记

我是从 python 2.7 开始接触的,要说python的各种历史,我还真的说不出来。 不过好在有 peps 记录了python的发展和进化。今天我们来挖挖 yield 的 历史。

PEP-255: 在2001年的时候, yield首次在python中出现。这时候的用法比较简单,只是单纯的作为 generator:

In [1]: def foo():
   ...:     for i in range(10):
   ...:         yield i
   ...:

In [2]: gen = foo()

In [3]: for i in gen:
   ...:     print(i, end=', ')
   ...:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,

这个时候yield的主要作用应该在于节省内存,例如查询数据库的时候,结果的数量非常 多,此时yield就可以发挥作用,在用到它的时候才产生数据。而不是像list一样保存 所有的数据。

PEP-380: 这个pep介绍了新的语法 yield from。他的作用主要是把对原本的generator产生作用的语句指向另外一个 generator,例如:

In [1]: def foo():
   ...:     for i in range(10):
   ...:         yield i
   ...:

In [2]: def bar():
   ...:     yield from foo()
   ...:

In [3]: gen = bar()

In [4]: for i in gen:
   ...:     print(i, end=', ')
   ...:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,

通过 yield from foo() 我们能直接从 bar() 这个generaotor里拿到 foo() 产 生的值。这也是传说中的代理模式的应用。


yield 和 yield from 有区别吗?什么时候该用哪个?

我们分别用一下:

In [1]: def foo():
   ...:     yield [1, 2, 3]
   ...:

In [2]: def bar():
   ...:     yield from [1, 2, 3]
   ...:

In [3]: for i in foo():
   ...:     print(i)
   ...:
[1, 2, 3]

In [4]: for i in bar():
   ...:     print(i)
   ...:
1
2
3

可以看出来,如果直接yield那是会直接把整个 [1, 2, 3] 给yield出来。什么时候 用yield什么时候用yield from傻傻分不清怎么办?有一个trick,但是如果你用这个 被主管打了可千万别怪我:

In [1]: class Future:
   ...:     pass
   ...:

In [2]: def foo():
   ...:     yield Future()
   ...:

In [3]: def bar():
   ...:     yield from Future()
   ...:

In [4]: for i in foo():
   ...:     pass
   ...:

In [5]: for i in bar():
   ...:     pass
   ...:
-------------------------------------------------------------------
TypeError                         Traceback (most recent call last)
<ipython-input-5-c0dd2fd4aa2d> in <module>()
----> 1 for i in bar():
      2     pass

<ipython-input-3-1c731241676c> in bar()
      1 def bar():
----> 2     yield from Future()
      3

TypeError: 'Future' object is not iterable

In [6]: class Future:
   ...:     def __iter__(self):
   ...:         yield self
   ...:

In [7]: for i in bar():
   ...:     pass
   ...:

In [8]:

为什么?因为

def foo():
    yield from bar()

几乎相当于

def foo():
    for i in bar():
        yield i

但是不同的是,yield from 会把对 foo() 作用的 next, .send, .throw 全部 传递给 bar() 但是后面一种形式不会,也就是说后面一种形式把代理这个动作几乎丢掉 了。