I'm trying to write my own awaiatbale function which could be used in an asyncio
loop like asyncio.sleep()
method or something like these pre-awaitable implemented methods.
Here is what I've done so far:
import asyncio
def coro1():
for i in range(1, 10):
yield i
def coro2():
for i in range(1, 10):
yield i*10
class Coro: # Not used.
def __await__(self):
for i in range(1, 10):
yield i * 100
@asyncio.coroutine
def wrapper1():
return (yield from coro1())
@asyncio.coroutine
def wrapper2():
return (yield from coro2())
for i in wrapper1():
print(i)
print("Above result was obvious which I can iterate around a couroutine.".center(80, "#"))
async def async_wrapper():
await wrapper1()
await wrapper2()
asyncio.run(async_wrapper())
What I got as a result:
1
2
3
4
5
6
7
8
9
#######Above result was obvious which I can iterate around a couroutine.#########
Traceback (most recent call last):
File "stack-coroutine.py", line 36, in <module>
result = loop.run_until_complete(asyncio.gather(*futures))
File "/usr/lib/python3.6/asyncio/base_events.py", line 484, in run_until_complete
return future.result()
File "stack-coroutine.py", line 30, in async_wrapper
await wrapper1()
File "stack-coroutine.py", line 18, in wrapper1
return (yield from coro1())
File "stack-coroutine.py", line 5, in coro1
yield i
RuntimeError: Task got bad yield: 1
What I expect as a result:
1
10
2
20
3
30
.
.
.
[NOTE]:
- I'm not looking for a multithread or multiprocess method.
- This Question is almost similar to my question which has not resolved yet.
async_wrapper
runs the two coroutines in sequence, not in parallel.asyncio.sleep()
). This code snippet is my effort to reach that. I would reach to mentioned result in my question with my own awaitable function.asyncio.sleep()
are implemented. I can also recommend this lecture that shows how the event loop works by building one from scratch, live. The code in the question shows misconceptions about how async/await works in Python, so it the question doesn't appear answerable at this point, at least not within the format of a normal StackOverflow answer.