Currently I am learning the python tornado, and I find an interesting def here , the sample code goes as
@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 ? How can we use this kind of 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
. Apparently, giving a value in return
just passes it as an argument to the StopIteration
exception.
It was pointed out in the comments that passing a value like this is only allowed since Python 3.3.
This value can't be seen in normal iteration (ie for x in f()
).
It seems like Tornado does something special with it, by iterating using next
and catching that exception. 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.
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. Tornado has a solution to this: you can yield and then raise gen.Return(value):
@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:
@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".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.