오늘도 개발
Asyncio와 비동기 작업 3) async with, async for 본문
1. Async Context Managers(async with)
context manager란?
리소스를 할당하고 사용할 수 있게 해주는 파이썬 기능.
예) 파일을 다룰 수 있게 해주는 with
with open('test.txt', 'w') as opened_file:
opened_file.write('Hi!')
비동기 context manager
앞에 async 붙여서 사용.
일반적인 with과 같지만, 코루틴을 await해서 setup과 teardown을 진행한다는 점이 다름.
async 코드 블럭(ex. 코루틴 함수 내) 안에서 사용 가능.
async with test.text as file:
async with file.open_read as reader:
texts = await reader.file(720, count=400)
2. Async Iterators(async for)
iterable
for loop로 iteration할 수 있는 객체. (= __iter__ 메서드를 갖는 객체, iterator를 갖는 객체)
예) list, dictionary, range...
async iterable은 async for loop로 iteration할 수 있는 객체.
코루틴으로 iterable을 생성하면 async iterable이 된다.
iterator
iterable이 __iter__로 생성한 객체.
__next__ 메서드를 갖기 때문에 값을 차례대로 꺼낼 수 있다.
iteration을 실제로 실행하는 역할을 한다.
async iterator는 __aiter__, __anext__메서드로 구현할 수 있다.
3. Async Generators(async for)
generator
iterator를 생성해주는 함수.
함수 안에 yield 키워드를 사용하면 제너레이터가 된다.
async generator
async와 yield 키워드를 사용하여 만든 제너레이터.
# async generator
async def gen_example(x, y):
yield x
yield y
# gen_example(1, 2)은 async iterator를 반환
# async iterator는 async for 구문에 사용할 수 있다.
async for item in gen_example(1, 2):
print(item)
# 1
# 2
async generator는 async generator 객체를 반환하는 동기 함수이다.
동기 함수이기 때문에 async generator에 await를 붙여 호출하면 오류가 난다.
async def coroutine_example(x):
return x
async def async_generator_example(x):
yield x
result1 = await coroutine_example(1) # 1
result2 = await async_generator_example(1) # Error - object async_generator can't be used in 'await' expression
async generator의 반환값은 async generator 객체이므로 async for 구문에 사용할 수 있다.
# async generator
async def gen_example(x, y):
yield x
yield y
async for item in gen_example(1, 2):
print(item)
# 1
# 2
참고
Python Asyncio Part 3 – Asynchronous Context Managers and Asynchronous Iterators
'웹 프로그래밍 > Python3' 카테고리의 다른 글
| Global Interpreter Lock(GIL) (0) | 2022.10.29 |
|---|---|
| Asyncio와 비동기 작업 4) multithreading과 run_in_executor 메서드 (0) | 2022.08.30 |
| Asyncio와 비동기 작업 2) Awaitables(Coroutine, Task, Future) (0) | 2022.08.24 |
| Asyncio와 비동기 작업 1) 개요 - 비동기적 처리란? 코루틴이란? (0) | 2022.08.23 |
| Iterator, Generator, Coroutine (0) | 2022.08.17 |