Search code examples
python-3.xperformanceasynchronous

When should i use async/await in Python?


Meta Context:

I'm building an api using aiohttp. Since it's an asynchronous framework, I have to use async to define handlers. Example:

async def index_handler(request):
    return web.Response(text="Hello, world")

app = web.Application()
app.router.add_route("GET", "/", index_handler)

Code Context:

During development, I found myself in a situation where i have nested function calls like so:

def bar():
    return "Hi"

async def foo():
    return bar()

await foo()

When I was thinking about performance, I didn't know whether or not I should do these nested functions all async as well. Example:

async def bar()
    return "Hi"

async def foo():
    return await bar()

await foo()

Question:

What is the best way to do nested function calls to optimize performance? Always use async/await or always use sync? Does this makes a difference?


Solution

  • Well in your case you dont need to async everything unless you have code that could potentially block things for example:

    def bar():
        """This function is not async because there is no need to."""
        return "Hi"
    
    async def foo():
        return bar()
    
    await foo()
    

    But if your function bar for examples sleeps or do some async functions inside, then you should async the function

    async def bar():
        """This function needs to be async because there 
        are operations that potentially could block"""
        await asyncio.sleep(1)
        return "Hi"
    
    async def foo():
        return bar()
    
    await foo()
    

    So for summarize, if you are using async operations you need to have a very clear idea of how your program runs and what it is doing in order to avoid to put async everywhere.