[英]Is it possible that a python def contains both “yield” and “return”?
Currently I am learning the python tornado, and I find an interesting def here , the sample code goes as 目前我正在学习python龙卷风,我在这里找到一个有趣的def,示例代码如下
@gen.coroutine
def fetch_coroutine(url):
http_client = AsyncHTTPClient()
response = yield http_client.fetch(url)
return response.bodyere
As you see the def function contains both yield and return... So, is it follow the python rules ? 如你所见,def函数包含yield和return ...那么,它是否遵循python规则? How can we use this kind of def ?
我们怎样才能使用这种def? anyone give me some samples will be very appreciate...
任何人给我一些样品将非常感谢...
>>> def f():
... yield 1
... return 2
...
>>> g = f()
>>> next(g)
1
>>> next(g)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration: 2
return
in a generator stops its execution and ends the iteration by raising a StopIteration
. 生成器中的
return
将停止执行并通过引发StopIteration
结束迭代。 Apparently, giving a value in return
just passes it as an argument to the StopIteration
exception. 显然,给一个值作为
return
只是将它作为参数传递给StopIteration
异常。
It was pointed out in the comments that passing a value like this is only allowed since Python 3.3. 在评论中指出 ,传递这样的值只能从Python 3.3开始。
This value can't be seen in normal iteration (ie for x in f()
). 在正常迭代中不能看到该值(即
for x in f()
)。
It seems like Tornado does something special with it, by iterating using next
and catching that exception. 看起来Tornado通过迭代使用
next
并捕获该异常来做一些特别的事情。 Coroutines are a complex topic. 协同程序是一个复杂的主题。 This could be the "result" of the coroutine, and the
yield
s in it would be just to suspend execution and exchange data. 这可能是协程的“结果”,其中的
yield
只是暂停执行和交换数据。
Not in Python 2. In Python 2, a function that contains "yield" can have a bare "return" with no value, but it is not allowed to return a value. 不在Python 2中。在Python 2中,包含“yield”的函数可以具有没有值的“返回”,但不允许返回值。 Tornado has a solution to this: you can yield and then raise gen.Return(value):
龙卷风有一个解决方案:你可以屈服然后提升gen.Return(价值):
@gen.coroutine
def fetch_coroutine(url):
http_client = AsyncHTTPClient()
response = yield http_client.fetch(url)
raise gen.Return(response.body)
In Python 3.3 and later, a function that contains "yield" can also return a value: 在Python 3.3及更高版本中,包含“yield”的函数也可以返回一个值:
@gen.coroutine
def fetch_coroutine(url):
http_client = AsyncHTTPClient()
response = yield http_client.fetch(url)
return response.body
Python 3.3 gained the ability to return a value from a generator in PEP 380 , along with the new statement "yield from". Python 3.3获得了从PEP 380中的生成器返回值的能力,以及新语句“yield from”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.