异步编程 - Python中的yield from的用法?
迷茫
迷茫 2017-04-18 10:04:59
0
4
423

对于yield from目前我只知道这一种用法,我对它的理解也停留在yield from generator

In [1]: def reader():
   ...:     """A generator that fakes a read from a file, socket, etc."""
   ...:     for i in range(4):
   ...:         yield '<< %s' % i
   ...:         

In [2]: def reader_wrapper(g):
   ...:     yield from g
   ...:     

In [3]: wrap = reader_wrapper(reader())

In [4]: for i in wrap:
   ...:     print(i)
   ...:     
<< 0
<< 1
<< 2
<< 3

但是在廖雪峰的异步IO教程中看见一个yield from的新用法,请问下面这个yield from asyncio.sleep(1)是什么意思,asyncio.sleep(1)也是一个生成器吗?看官方文档也没有给出明确的解释,也是直接贴的代码,拜托大神解释一下!

import asyncio

@asyncio.coroutine
def hello():
    print("Hello world!")
    # 异步调用asyncio.sleep(1):
    r = yield from asyncio.sleep(1)
    print("Hello again!")

# 获取EventLoop:
loop = asyncio.get_event_loop()
# 执行coroutine
loop.run_until_complete(hello())
loop.close()
迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(4)
刘奇

First find the definition of asyncio.sleep() function

coroutine asyncio.sleep(delay, result=None, *, loop=None)

That is to say, this function is a coroutine function. The coroutine function can be called like this to get the return value

result = await coroutine or result = yield from coroutine 

As for why it can be used in this way?

  1. await itself is a keyword used in coroutines.

  2. can use the yield keyword because the implementation of coroutine is generator-based. As for why yield from is used instead of the original yield, this must have a source. You can see PEP380. All in all, it is troublesome to use yield to obtain coroutine information, so I added a yield from to simplify the operation.
    https://www.python.org/dev/pe...

To summarize: You can use yield because coroutine is generator-based, so it’s not wrong to say that sleep returns generator. Why does from appear? It’s because only yield is too Trouble, you can think of it as syntax sugar. For details, please see PEP8.

PS: Just a few words at the end, this is why I don’t recommend reading blogs to learn a language. It’s also free. Why not choose the more authoritative and detailed official Python documentation?

PHPzhong

The essence of coroutine is a generator

You can watch this video~
Explore the implementation of async/await feature in Python 3.5

PHPzhong

Why do you need to package it once?

for i in reader():
    print(i)

Can this also be used? Very puzzled. . .

巴扎黑

You can read this article written by the Python author, rough translation

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!