Python고급 주제

async/await 기본 패턴

`async def`과 `await`을 이용한 비동기 함수 작성과 `asyncio.gather` 활용을 정리합니다.

마지막 수정 2026년 3월 17일

기본 패턴

python
import asyncio

async def fetch_data():
    await asyncio.sleep(0.5)
    return "data"

async def main():
    resulta, resultb = await asyncio.gather(fetch_data(), fetch_data())
    print(resulta, resultb)

asyncio.run(main())

설명

  • async def로 coroutine을 정의하고, await을 통해 다른 coroutine이나 asyncio.sleep, aiohttp 등의 awaitable을 기다립니다.
  • asyncio.run은 최상위 entry point이고, asyncio.gather로 여러 awaitable을 동시에 실행할 수 있습니다.
  • asyncio.create_task로 백그라운드 태스크를 만들어 다른 작업과 병렬로 돌릴 수도 있습니다.

짧은 예제

python
async def poll():
    while True:
        print("polling")
        await asyncio.sleep(1)

asyncio.create_task(poll())
await fetch_data()

빠른 정리

키워드역할
async defcoroutine 정의
awaitawaitable 결과 기다리기
asyncio.run루프 실행
gather여러 coroutine 병렬

주의할 점

동기 함수 안에서 await을 직접 쓸 수 없으므로, 필요하면 asyncio.run으로 감싼 coroutine을 호출하거나 loop.create_task를 쓰세요.