Why do we need the asyncio.coroutine decorator?

Why do we need a decorator asyncio.coroutine? What functionality does it provide?

For instance:

# import asyncio
# @asyncio.coroutine
def gen():
    value = yield("Started")
    print(value)

a = gen()
a.send(None)
a.send("Done")

Now, if I uncomment the first two lines and use the decorator asyncio.coroutine, I still get the same result.

I mean, this is already coroutinea function that can be paused and passed by argument. Why do I need to decorate it with another coroutineie asyncio.coroutine?

+4
source share
1 answer

, generators asyncio coroutines - . , () . Genarators - .

asyncio , :

import asyncio


def main():
    yield from asyncio.sleep(1)
    print('done')


loop = asyncio.get_event_loop()
loop.run_until_complete(main())

:

done

:

import asyncio


def main():
    # yield from asyncio.sleep(1)
    print('done')


loop = asyncio.get_event_loop()
loop.run_until_complete(main())

:

TypeError: An asyncio.Future, a coroutine or an awaitable is required

( ) asyncio.coroutine decorator :

import asyncio


@asyncio.coroutine
def main():
    # yield from asyncio.sleep(1)
    print('done')


loop = asyncio.get_event_loop()
loop.run_until_complete(main())

:

done

, , : Python 3.5 yield from async def await, , .

import asyncio


async def main():
    # await asyncio.sleep(1)
    print('done')


loop = asyncio.get_event_loop()
loop.run_until_complete(main())
+4

Source: https://habr.com/ru/post/1688752/


All Articles