PHpullh
학습 라이브러리/Python/async/await 심화

PYTHON · 비동기

async/await 심화

async/await의 고급 패턴: 에러 처리, 타임아웃, 동시 실행 제어를 다룹니다.

비동기중급asyncawaittimeoutgather

핵심 설명

async/await의 고급 패턴: 에러 처리, 타임아웃, 동시 실행 제어를 다룹니다.

Python code

import asyncio

async def fetch(url: str, delay: float) -> dict:
    await asyncio.sleep(delay)  # 네트워크 요청 시뮬레이션
    if "error" in url:
        raise ConnectionError(f"{url} 연결 실패")
    return {"url": url, "status": 200}

async def main():
    # 타임아웃 설정
    try:
        result = await asyncio.wait_for(
            fetch("https://slow.api", 10), timeout=2.0
        )
    except asyncio.TimeoutError:
        print("타임아웃 발생!")

    # gather로 에러 처리
    results = await asyncio.gather(
        fetch("https://api1.com", 1),
        fetch("https://error.api", 1),
        fetch("https://api3.com", 0.5),
        return_exceptions=True,  # 예외를 결과로 반환
    )
    for r in results:
        if isinstance(r, Exception):
            print(f"  에러: {r}")
        else:
            print(f"  성공: {r}")

    # as_completed: 먼저 끝나는 순서대로
    tasks = [
        asyncio.create_task(fetch(f"https://api{i}.com", 3-i))
        for i in range(3)
    ]
    for coro in asyncio.as_completed(tasks):
        result = await coro
        print(f"  완료: {result['url']}")

asyncio.run(main())

학습 팁

return_exceptions=True를 사용하면 하나의 실패가 전체를 중단시키지 않습니다.

주의할 점

await 없이 코루틴을 호출하면 실행되지 않고 코루틴 객체만 반환됩니다. 반드시 await하세요.

자주 묻는 질문

async/await 심화란 무엇인가요?

async/await 의 고급 패턴: 에러 처리, 타임아웃, 동시 실행 제어를 다룹니다.

async/await 심화 학습 시 주의할 점은 무엇인가요?

await 없이 코루틴을 호출하면 실행되지 않고 코루틴 객체만 반환됩니다. 반드시 await 하세요.