带有返回语句的生成器 [英] Generator with return statement
问题描述
在报道期间,我在以下案例(python 3.4)上挠头了
During my coverage, I scratched my head on the following case (python 3.4)
def simple_gen_function(str_in, sep=""):
if sep == "":
yield str_in[0]
for c in str_in[1:]:
yield c
else:
return str_in
# yield from str_in
str_in = "je teste "
t = "".join(simple_gen_function(str_in))
p = "".join(simple_gen_function(str_in, "\n"))
print("%r %r" % (t, p))
# 'je teste' ''
使用生成器中的return,在使用yield from str_in
时未达到"返回值,我得到了预期的结果.
Using return in the generator, the return was not "reached" while using yield from str_in
I have the expected result.
这个问题似乎很简单,但是我相信在生成器中使用return可以实现.
The question seems simple, but I believed that using return in a generator, it was in reached.
推荐答案
在函数主体中yield
的存在将其转变为生成器函数,而不是普通函数.在生成器函数中,使用return
表示生成器已结束,没有更多元素了".通过将生成器方法的第一条语句设为return str_in
,可以确保您拥有不返回任何元素的生成器.
The presence of yield
in a function body turns it into a generator function instead of a normal function. And in a generator function, using return
is a way of saying "The generator has ended, there are no more elements." By having the first statement of a generator method be return str_in
, you are guaranteed to have a generator that returns no elements.
正如评论所提到的,返回值 用作StopIteration
异常的参数,该异常在生成器结束时引发.参见:
As a comment mentions, the return value is used as an argument to the StopIteration
exception that gets raised when the generator has ended. See:
>>> gen = simple_gen_function("hello", "foo")
>>> next(gen)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration: hello
如果def
中任何位置都有yield
,则它是生成器!
在注释中,提问者提到他们认为执行yield语句时,该函数动态地变成了生成器.但这不是它的工作方式!该决定是在代码被执行之前做出的.如果Python在def
下的任何位置都找到了yield
,它将把def
变成生成器函数.
If there's a yield
anywhere in your def
, it's a generator!
In the comments, the asker mentions they thought the function turned into a generator dynamically, when the yield statement is executed. But this is not how it works! The decision is made before the code is ever excuted. If Python finds a yield
anywhere at all under your def
, it turns that def
into a generator function.
请参见以下简短示例:
>>> def foo():
... if False:
... yield "bar"
... return "baz"
>>> foo()
<generator object foo at ...>
>>> # The return value "baz" is only exposed via StopIteration
>>> # You probably shouldn't use this behavior.
>>> next(foo())
Traceback (most recent call last):
...
StopIteration: baz
>>> # Nothing is ever yielded from the generator, so it generates no values.
>>> list(foo())
[]
这篇关于带有返回语句的生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!