0

Here is a block of code from: https://github.com/ronf/asyncssh/blob/master/examples/math_server.py#L38

async def handle_client(process):
    process.stdout.write('Enter numbers one per line, or EOF when done:\n')

    total = 0

    try:
        async for line in process.stdin:
            line = line.rstrip('\n')
            if line:
                try:
                    total += int(line)
                except ValueError:
                    process.stderr.write('Invalid number: %s\n' % line)
    except asyncssh.BreakReceived:
        pass

There is an async keyword before the def, however there is also one before the for loop. In looking at the documentation for asyncio here: https://docs.python.org/3/library/asyncio-task.html, I do not see any similar uses of this async keyword.

So, what does the keyword do in this context?

1
  • This is explained in PEP 492. Commented Feb 28, 2019 at 17:35

1 Answer 1

1

The async for ... in ... construct allows you to loop through "Asynchronous iterable" and as stated in comments, detailed explanation is in PEP 492

In your example case, the async for loop, waits for stdin input, while not blocking other asyncio-loop tasks. If you would use for loop, this would be blocking operation and no other tasks on the loop could be executed unit you've entered input.


To get another example, imagine MySQL client fetching x rows from database. aio-mysql example

async for row in conn.execute("SELECT * FROM table;"):
    print(row)

This fetches single row, and it isn't blocking the execution of other tasks on the asyncio-loop, while waiting for IO operations (mysql query).

Then you do something with the row data you've obtained.

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

3 Comments

It might make sense to clarify that in "loop tasks" loop refer to the asyncio event loop, not the async for loop. Contrary to expectations of many beginners, an async for loop is still completely sequential - as sequential as, say, a while loop containing awaits - it just allows other tasks to run (as stated in the answer).
Thanks for the notice of the asyncio-loop. Feel free to edit the answer :)
object type you iterate must have __anext__ magical method defined

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.