Can Python asyncio.coroutine be considered a generator?

I googled python coroutine and saw only generators (almost all examples use yield without asyncio .)

Are they the same?

What is the difference between asyncio.coroutine and a generator?

+6
source share
1 answer

Most coroutine implementations in Python (including those provided by asyncio and tornado ) are implemented using generators. This was so because PEP 342 - Coroutines through Enhanced Generators allowed us to send values ​​to running objects of the generator, which allowed us to implement simple coroutines. Coroutines are technically generators; they are just designed to be used in a completely different way. In fact, the PEP for asyncio explicitly states this :

Corutin is a generator that follows certain conventions.

asyncio.coroutine is a generator. Pretty literally:

 >>> import asyncio >>> @asyncio.coroutine ... def mycoro(): ... yield from asyncio.sleep(1) ... >>> a = mycoro() >>> a <generator object mycoro at 0x7f494b5becf0> 

The difference, again, is how the two things are meant to be used. Trying to iterate over asyncio.coroutine , like a regular generator, will not work:

 >>> next(a) Future<PENDING> >>> next(a) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in mycoro File "/usr/lib/python3.4/asyncio/tasks.py", line 548, in sleep return (yield from future) File "/usr/lib/python3.4/asyncio/futures.py", line 349, in __iter__ assert self.done(), "yield from wasn't used with future" AssertionError: yield from wasn't used with future 

It is clear that you are not going to sort it out. You mean only yield from or register it in the asyncio event asyncio using asyncio.create_task or asyncio.async .

As I mentioned earlier, it was possible to implement coroutines using generators, since PEP 342, which was long before asyncio or yield from came; This feature was added back in 2005. asyncio and yield from simply add features that make email composing easier.

+3
source

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


All Articles