1

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.

3
  • Is this really the right approach for you? I think there must be other ways for you to learn the async await syntax, that don't require you to implement your own version of asyncio Nov 16, 2018 at 23:44
  • Hope if i'll got what is under the hood, I'll got the concept itself. Without it looks like pure magic.
    – john.don83
    Nov 17, 2018 at 0:03
  • 1
    I could be wrong, but I think you will be happier if you embrace encapsulation and learn APIs and interfaces instead of internals, at least at first. There's nothing wrong with looking at the internals, but I think that is learning the async await pattern the very hard way. The metaphor I was taught was to think of a lightswitch when we talk about encapsulation: it is easier to learn how to use a lightswitch than how the wires fit together behind the panel. Nov 17, 2018 at 0:18

1 Answer 1

2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.