Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 471
Nicolas Caous Avatar asked Jul 27 '26 18:07

Nicolas Caous


1 Answers

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.

like image 163
camp0 Avatar answered Jul 30 '26 10:07

camp0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!