Python: Can async/await mimic this generator based solution?

Viewed 97

Imagine you have a function that says, start running this function in the update step of your event loop. You want to pause execution of this function, until that function has ended (or you've received some signal from it). You should still update the rest of the real-time updating functions simultaneously with the new function.

I've created a working solution using generators, but in the interest of trying to understand how async/await works in Python, I'm curious if there's a solution involving those keywords. I don't particularly understand if async/await yields execution back to the calling function. From my testing, I don't think it does, but I'd love to understand them and yield from a bit better.

Note: The global variables are simply for the small example. This will be wrapped in a command pattern in the actual use.

import time

start_update = False
flag = False
cur = 0.0


def update(delta):
    global cur
    global flag

    cur += delta
    print(cur)
    if cur > 0.5:
        flag = True
        print("setting flag")


def do_something():
    global start_update
    global flag

    print("Do some pre stuff")
    start_update = True

    while not flag:
        yield False

    print("Do some stuff after")
    yield True


def main():
    global flag

    last_time = time.time()
    held_func = None
    complete = False

    while True:
        now = time.time()
        delta = now - last_time
        last_time = now

        if start_update:
            update(delta)

        if held_func is not None:
            try:
                complete = next(held_func)
            except StopIteration:
                pass
        else:
            held_func = do_something()
            next(held_func)

        if complete:
            break


if __name__ == "__main__":
    main()
0 Answers
Related