python - 为什么这个递归 ```yield from``` 函数不会引发错误?
问题描述
def prefixes(s):
if s:
yield from prefixes(s[:-1])
yield s
t = prefixes('both')
next(t)
下一个(t)返回'b'。我只是对为什么会这样感到困惑,因为如果我们遵循yield from
声明,我们最终yield from prefixes('')
会以返回 None 结束。在我的所有其他测试中,从 None 产生的结果会引发 TypeError。相反,这似乎只是被忽略了,并且 prefixes('b') 移动到下一个 yield 语句(?为什么这样做?)以产生 'b'...关于为什么的任何想法?将不胜感激解释。
解决方案
发电机是惰性(按需)对象,你没有用尽你的发电机t
,你可以使用你的发电机:
list(t)
# ['b', 'bo', 'bot', 'both']
现在如果你使用next(t)
你会得到预期的StopIteration
StopIteration Traceback (most recent call last)
<ipython-input-25-680ef78477e2> in <module>
6 t = prefixes('both')
7 list(t)
----> 8 next(t)
StopIteration:
该if
声明是“保证”你有一个结束,你永远不会None[:-1]
做得到TypeError
推荐阅读
- android - Kotlin,应用程序存储:需要存储来自用户交互的整数的 ArrayList
- javascript - 将数据显示到页面的 Vue 功能不起作用
- node.js - 当我在 NODE.JS 中快速多次按下按钮时的奇怪行为
- r - 在 Linux 中安装 R 包的问题
- reactjs - 如何使用 AWS Amplify for SPA reactjs 应用程序创建批处理查询
- javascript - 如何在 laravel 8 中使用来自 npm 的 twitter 引导程序
- elasticsearch - 序列化响应时,BucketAggregate 上的“键”丢失
- bootstrap-4 - 带有引导程序的 Tampermonkey 脚本不起作用
- c++ - f(T&()) 的模板参数推导是如何发生的?
- android - 从协程范围返回值而不使用 runBlocking