john.don83
john.don83

Reputation: 123

Python 3.6 async await without asyncio: how to write own simplest event loop?

Just like to understand async await syntax, so I am looking for some 'hello world' app without using asyncio at all.

So how to create simplest event loop using only Python syntax itself? The simplest code (from this Start async function without importing the asyncio package , further code is much more then hello world, that's why I am asking) looks like that:

async def cr():
    while(True):
        print(1)

cr().send(None)

It prints 1 infinitely, not so good.

So the 1st question is how to yield from coroutine back to the main flow? yield keyword makes coroutine async generator, not we expected.

I would also appreciate a simple application, like this i.e. we have a coroutine which prints 1, then yields to event loop, then prints 2 then exits with return 3, and simple event loop, which push coroutine until return and consume result.

Upvotes: 1

Views: 1324

Answers (1)

Veky
Veky

Reputation: 2755

How about this?

import types

@types.coroutine
def simple_coroutine():
    print(1)
    yield
    print(2)
    return 3

future = simple_coroutine()
while True:
    try: future.send(None)
    except StopIteration as returned:
        print('It has returned', returned.value)
        break

I think your biggest problem is that you're mixing concepts. An async function is not the same as a coroutine. It is more appropriate to think of it as a way of combining coroutines. Same as ordinary def functions are a way of combining statements into functions. Yes, Python is highly reflective language, so def is also a statement, and what you get from your async function is also a coroutine---but you need to have something at the bottom, something to start with. (At the bottom, yielding is just yielding. At some intermediate level, it is awaiting---of something else, of course.) That's given to you through the types.coroutine decorator in the standard library.

If you have any more questions, feel free to ask.

Upvotes: 2

Related Questions