Python · Синтаксис · Продвинутый уровень
Асинхронный Python
Пишите конкурентные программы с `async def`, `await` и `asyncio`. Охватывает корутины, `asyncio.gather`, задачи, `asyncio.Queue` и асинхронные итераторы.
Краткое введение в тему и пояснения перед упражнениями (упражнения ниже):
Tasks, async for/with, таймаут, конкурентные HTTP-запросы
#Частые ошибки, asyncio vs потоки vs multiprocessing, справочник
#Упражнения:
Первая корутина с asyncio.run
#import asyncio
async def greet(name: str) -> None:
pass
asyncio.run(greet('Алиса'))
# Привет, Алиса!
# До свидания, Алиса!
Решение
import asyncio
async def greet(name: str) -> None:
print(f'Привет, {name}!')
await asyncio.sleep(0.1)
print(f'До свидания, {name}!')
asyncio.run(greet('Алиса'))
# Привет, Алиса!
# До свидания, Алиса!
Конкурентные задачи с asyncio.gather
#import asyncio
async def fetch(url: str, delay: float) -> str:
pass
async def main() -> None:
results = await asyncio.gather(
fetch('A', 0.3),
fetch('B', 0.1),
fetch('C', 0.2),
)
for r in results:
print(r)
asyncio.run(main())
Решение
import asyncio
async def fetch(url: str, delay: float) -> str:
await asyncio.sleep(delay)
return f'Response from {url}'
async def main() -> None:
results = await asyncio.gather(
fetch('A', 0.3),
fetch('B', 0.1),
fetch('C', 0.2),
)
for r in results:
print(r)
asyncio.run(main())
# Response from A
# Response from B
# Response from C
Фоновые задачи с create_task
#import asyncio
async def countdown() -> None:
for i in range(3, 0, -1):
print(f'Обратный отсчёт: {i}')
await asyncio.sleep(0.1)
async def worker() -> None:
for _ in range(3):
print('Работаем...')
await asyncio.sleep(0.15)
async def main() -> None:
# создайте задания и дождитесь их
pass
asyncio.run(main())
Решение
import asyncio
async def countdown() -> None:
for i in range(3, 0, -1):
print(f'Обратный отсчёт: {i}')
await asyncio.sleep(0.1)
async def worker() -> None:
for _ in range(3):
print('Работаем...')
await asyncio.sleep(0.15)
async def main() -> None:
task1 = asyncio.create_task(countdown())
task2 = asyncio.create_task(worker())
await task1
await task2
asyncio.run(main())
Производитель-потребитель с asyncio.Queue
#import asyncio
async def producer(queue: asyncio.Queue) -> None:
pass
async def consumer(queue: asyncio.Queue) -> None:
pass
async def main() -> None:
queue: asyncio.Queue = asyncio.Queue()
await asyncio.gather(producer(queue), consumer(queue))
asyncio.run(main())
Решение
import asyncio
async def producer(queue: asyncio.Queue) -> None:
for i in range(1, 6):
await queue.put(i)
await asyncio.sleep(0.05)
await queue.put(None) # сигнал завершения
async def consumer(queue: asyncio.Queue) -> None:
while True:
item = await queue.get()
if item is None:
break
print(f'Consuming: {item}')
async def main() -> None:
queue: asyncio.Queue = asyncio.Queue()
await asyncio.gather(producer(queue), consumer(queue))
asyncio.run(main())
Таймаут с asyncio.wait_for
#import asyncio
async def slow_op(seconds: float) -> str:
await asyncio.sleep(seconds)
return 'done'
async def main() -> None:
try:
result = await asyncio.wait_for(slow_op(5), timeout=0.2)
print(result)
except asyncio.TimeoutError:
pass # выведите сообщение здесь
asyncio.run(main())
# Operation timed out!
Решение
import asyncio
async def slow_op(seconds: float) -> str:
await asyncio.sleep(seconds)
return 'done'
async def main() -> None:
try:
result = await asyncio.wait_for(slow_op(5), timeout=0.2)
print(result)
except asyncio.TimeoutError:
print('Operation timed out!')
asyncio.run(main())
# Operation timed out!
Асинхронный генератор
#import asyncio
async def async_range(start: int, stop: int, delay: float):
pass
async def main() -> None:
async for value in async_range(0, 4, 0.05):
print(value)
asyncio.run(main())
# 0
# 1
# 2
# 3
Решение
import asyncio
async def async_range(start: int, stop: int, delay: float):
for i in range(start, stop):
yield i
await asyncio.sleep(delay)
async def main() -> None:
async for value in async_range(0, 4, 0.05):
print(value)
asyncio.run(main())
Асинхронный контекстный менеджер
#import asyncio
import time
class AsyncTimer:
async def __aenter__(self):
pass
async def __aexit__(self, *args):
pass
async def main() -> None:
async with AsyncTimer():
await asyncio.sleep(0.1)
asyncio.run(main())
# Timer started
# Elapsed: 0.10s
Решение
import asyncio
import time
class AsyncTimer:
async def __aenter__(self):
self._start = time.perf_counter()
print('Timer started')
return self
async def __aexit__(self, *args):
elapsed = time.perf_counter() - self._start
print(f'Elapsed: {elapsed:.2f}s')
async def main() -> None:
async with AsyncTimer():
await asyncio.sleep(0.1)
asyncio.run(main())
Ограничение конкурентности с asyncio.Semaphore
#import asyncio
async def task(n: int, sem: asyncio.Semaphore) -> None:
async with sem:
print(f'Task {n} started')
await asyncio.sleep(0.1)
print(f'Task {n} done')
async def main() -> None:
sem = asyncio.Semaphore(3)
# создайте и запустите 8 задач (n от 1 до 8)
pass
asyncio.run(main())
Решение
import asyncio
async def task(n: int, sem: asyncio.Semaphore) -> None:
async with sem:
print(f'Task {n} started')
await asyncio.sleep(0.1)
print(f'Task {n} done')
async def main() -> None:
sem = asyncio.Semaphore(3)
await asyncio.gather(*(task(n, sem) for n in range(1, 9)))
asyncio.run(main())
Выполнение блокирующего кода через run_in_executor
#import asyncio
def blocking_sum(n: int) -> int:
return sum(range(n + 1))
async def async_sum(n: int) -> int:
loop = asyncio.get_running_loop()
# запустите blocking_sum в пуле потоков
pass
async def main() -> None:
results = await asyncio.gather(async_sum(1000), async_sum(2000))
print(results) # [500500, 2001000]
asyncio.run(main())
Решение
import asyncio
def blocking_sum(n: int) -> int:
return sum(range(n + 1))
async def async_sum(n: int) -> int:
loop = asyncio.get_running_loop()
return await loop.run_in_executor(None, blocking_sum, n)
async def main() -> None:
results = await asyncio.gather(async_sum(1000), async_sum(2000))
print(results) # [500500, 2001000]
asyncio.run(main())
Координация с asyncio.Event
#import asyncio
async def setter(event: asyncio.Event) -> None:
await asyncio.sleep(0.15)
print('Setting event')
event.set()
async def waiter(event: asyncio.Event) -> None:
pass # дождитесь события, затем выведите 'Event received!'
async def main() -> None:
event = asyncio.Event()
await asyncio.gather(setter(event), waiter(event))
asyncio.run(main())
Решение
import asyncio
async def setter(event: asyncio.Event) -> None:
await asyncio.sleep(0.15)
print('Setting event')
event.set()
async def waiter(event: asyncio.Event) -> None:
print('Waiting for event...')
await event.wait()
print('Event received!')
async def main() -> None:
event = asyncio.Event()
await asyncio.gather(setter(event), waiter(event))
asyncio.run(main())