sim16/matteo_env/Lib/site-packages/aiohttp/locks.py

42 lines
1.1 KiB
Python
Raw Normal View History

2020-12-20 00:08:09 +00:00
import asyncio
import collections
2022-09-18 13:17:20 +00:00
from typing import Any, Deque, Optional
2020-12-20 00:08:09 +00:00
class EventResultOrError:
2022-09-18 13:17:20 +00:00
"""Event asyncio lock helper class.
Wraps the Event asyncio lock allowing either to awake the
2020-12-20 00:08:09 +00:00
locked Tasks without any error or raising an exception.
thanks to @vorpalsmith for the simple design.
"""
2022-09-18 13:17:20 +00:00
2020-12-20 00:08:09 +00:00
def __init__(self, loop: asyncio.AbstractEventLoop) -> None:
self._loop = loop
self._exc = None # type: Optional[BaseException]
2022-09-18 13:17:20 +00:00
self._event = asyncio.Event()
2020-12-20 00:08:09 +00:00
self._waiters = collections.deque() # type: Deque[asyncio.Future[Any]]
2022-09-18 13:17:20 +00:00
def set(self, exc: Optional[BaseException] = None) -> None:
2020-12-20 00:08:09 +00:00
self._exc = exc
self._event.set()
async def wait(self) -> Any:
waiter = self._loop.create_task(self._event.wait())
self._waiters.append(waiter)
try:
val = await waiter
finally:
self._waiters.remove(waiter)
if self._exc is not None:
raise self._exc
return val
def cancel(self) -> None:
2022-09-18 13:17:20 +00:00
"""Cancel all waiters"""
2020-12-20 00:08:09 +00:00
for waiter in self._waiters:
waiter.cancel()