3

I'm new to Python3 asyncio.

I have a function that constantly retrieves messages from a websocket connection.

I'm wondering whether I should use a while True loop or asyncio.ensure_future in a recursive manner.

Which is preferred or does it not matter?

Example:

async def foo(websocket):
    while True:
        msg = await websocket.recv()
        print(msg)
        await asyncio.sleep(0.0001)

or

async def foo(websocket):
    msg = await websocket.recv()
    print(msg)
    await asyncio.sleep(0.0001)
    asyncio.ensure_future(foo(websocket))
1
  • It's ok to just asyncio.sleep(0) to yield the control back to the loop. No need to use 0.0001 Commented Mar 16, 2023 at 2:34

1 Answer 1

4

I would recommend the iterative variant, for two reasons:

  1. It is easier to understand and extend. One of the benefits of coroutines compared to callback-based futures is that they permit the use of familiar control structures like if and while to model the code's execution. If you wanted to change your code to e.g. add an outer loop around the existing one, or to add some code (e.g. another loop) after the loop, that would be considerably easier in the non-recursive version.

  2. It is more efficient. Calling asyncio.ensure_future(foo(websocket)) instantiates both a new coroutine object and a brand new task for each new iteration. While neither are particularly heavy-weight, all else being equal, it is better to avoid unnecessary allocation.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.