How to Create Async Function in Python: Simple Guide
In Python, you create an async function by using the
async def syntax before the function name. This marks the function as asynchronous, allowing you to use await inside it to pause execution until asynchronous operations complete.Syntax
An async function in Python is defined using the async def keywords followed by the function name and parentheses. Inside this function, you can use await to wait for asynchronous tasks to finish without blocking the whole program.
- async def: marks the function as asynchronous.
- function_name(): the name and parameters of the function.
- await: pauses the function until the awaited task completes.
python
async def my_async_function(): await some_async_task()
Example
This example shows an async function that waits for 1 second before printing a message. It uses asyncio.sleep() to simulate an asynchronous delay.
python
import asyncio async def greet(): print("Waiting to greet...") await asyncio.sleep(1) # Wait asynchronously for 1 second print("Hello from async function!") asyncio.run(greet())
Output
Waiting to greet...
Hello from async function!
Common Pitfalls
Common mistakes include forgetting to use async before def, trying to call async functions without await, or running async functions without an event loop.
For example, calling an async function like a normal function returns a coroutine object but does not run it.
python
import asyncio # Wrong: missing async keyword # def wrong_func(): # await asyncio.sleep(1) # SyntaxError # Wrong: calling async function without await async def say_hi(): print("Hi") result = say_hi() # This returns a coroutine, does not run it print(result) # Output: <coroutine object say_hi at 0x...> # Right way: async def say_hi_correct(): print("Hi Correct") asyncio.run(say_hi_correct())
Output
<coroutine object say_hi at 0x7f...>
Hi Correct
Quick Reference
| Keyword | Purpose |
|---|---|
| async def | Defines an asynchronous function |
| await | Waits for an async operation to complete |
| asyncio.run() | Runs the async function in an event loop |
| coroutine | An async function call returns a coroutine object |
Key Takeaways
Use
async def to define an asynchronous function in Python.Inside async functions, use
await to pause until async tasks finish.Always run async functions with an event loop like
asyncio.run().Calling an async function without
await returns a coroutine, not the result.Forget not to mark functions as async if you want to use await inside them.