[Python] Simplest async/await example possible in Python

Discussão em 'Python' iniciado por Stack, Março 5, 2025.

  1. Stack

    Stack Membro Participativo

    I've read many examples, blog posts, questions/answers about asyncio / async / await in Python 3.5+, many were complex, the simplest I found was probably this one.
    Still it uses ensure_future, and for learning purposes about asynchronous programming in Python, I would like to see an even more minimal example, and what are the minimal tools necessary to do a basic async / await example.

    Question: is it possible to give a simple example showing how async / await works, by using only these two keywords + code to run the async loop + other Python code but no other asyncio functions?

    Example: something like this:

    import asyncio

    async def async_foo():
    print("async_foo started")
    await asyncio.sleep(5)
    print("async_foo done")

    async def main():
    asyncio.ensure_future(async_foo()) # fire and forget async_foo()
    print('Do some actions 1')
    await asyncio.sleep(5)
    print('Do some actions 2')

    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())


    but without ensure_future, and still demonstrates how await / async works.

    Continue reading...

Compartilhe esta Página