首页 > 解决方案 > 为什么这个递归 ```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'...关于为什么的任何想法?将不胜感激解释。

标签: pythonrecursionyieldyield-from

解决方案


发电机是惰性(按需)对象,你没有用尽你的发电机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


推荐阅读