Sobes.tech
Junior — Middle

What is the difference between declaring a function with async def and a regular function with def in Python?

sobes.tech AI

Answer from AI

Declaring a function with async def in Python creates an asynchronous function (coroutine) that can be called using await within an asynchronous context. A regular function with def is synchronous and executes immediately upon call.

Main differences:

  • async def allows writing non-blocking code, for example, for input/output (I/O), network requests, etc.
  • An asynchronous function returns a coroutine, which needs to be run using await or in an event loop.
  • A synchronous function executes fully upon call and blocks the thread until completion.

Example:

import asyncio

async def async_func():
    await asyncio.sleep(1)
    return 'async result'

def sync_func():
    import time
    time.sleep(1)
    return 'sync result'

async def main():
    result = await async_func()
    print(result)

asyncio.run(main())