Python中的产量中断 [英] yield break in Python
问题描述
根据对此问题的回答, C#中的yield break
等同于Python中的return
.在正常情况下,return
确实会停止生成器.但是,如果您的函数只执行return
,则将得到一个None
而不是一个空的迭代器,该迭代器由C#中的yield break
返回
According to answer to this question, yield break
in C# is equivalent to return
in Python. In the normal case, return
indeed stops a generator. But if your function does nothing but return
, you will get a None
not an empty iterator, which is returned by yield break
in C#
def generate_nothing():
return
for i in generate_nothing():
print i
您将获得一个TypeError: 'NoneType' object is not iterable
,
但是,如果我添加并且从未在return
之前运行yield
,则此函数将返回我期望的结果.
You will get a TypeError: 'NoneType' object is not iterable
,
but if I add and never run yield
before return
, this function returns what I expect.
def generate_nothing():
if False: yield None
return
它有效,但看起来很奇怪.你有更好的主意吗?
It works, but seems weird. Do you have a better idea?
推荐答案
def generate_nothing():
return
yield
这篇关于Python中的产量中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!