“可迭代的收益”与“可迭代的收益”

“可迭代的收益”与“可迭代的收益”,第1张

“可迭代的收益”与“可迭代的收益”

唯一的显着区别是,当从可迭代对象内部引发异常时会发生什么。使用

returniter()
your
FancyNewClass
将不会出现在异常回溯中,而将会出现在异常回溯中
yieldfrom
。在尽可能多的回溯中获得信息通常是一件好事,尽管在某些情况下您可能希望隐藏包装器。

其他差异:

  • return iter
    必须
    iter
    从全局变量中加载名称-这可能很慢(尽管不太可能显着影响性能),并且可能会引起混乱(尽管像这样覆盖全局变量的任何人都应该得到它们)。

  • 使用,

    yield from
    您可以
    yield
    在之前和之后插入其他表达式(尽管您可以同等使用
    itertools.chain
    )。

  • 如前所述,该

    yield from
    表单会舍弃任何生成器返回值(即
    raise StopException(value)
    ,您可以通过编写来解决此问题
    return (yield from iterator)

这是一个比较两种方法的反汇编并显示异常回溯的测试:http :
//ideone.com/1YVcSe

使用

return iter()

  30 LOAD_GLOBAL   0 (iter)   3 LOAD_FAST     0 (it)   6 CALL_FUNCTION 1 (1 positional, 0 keyword pair)   9 RETURN_VALUETraceback (most recent call last):  File "./prog.py", line 12, in test  File "./prog.py", line 10, in iRuntimeError

使用

return (yield from)

  50 LOAD_FAST     0 (it)   3 GET_ITER   4 LOAD_ConST    0 (None)   7 YIELD_FROM   8 RETURN_VALUETraceback (most recent call last):  File "./prog.py", line 12, in test  File "./prog.py", line 5, in bar  File "./prog.py", line 10, in iRuntimeError


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5617900.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存