From 2466c20059df9d7e518d11d6c27d3ca5afea32d0 Mon Sep 17 00:00:00 2001 From: Aleksander Wasaznik Date: Sun, 5 Feb 2017 15:49:27 +0100 Subject: [PATCH] Create nyasync library The library contains helpers for more ergonomic use of asyncio. --- grzegorz/nyasync.py | 48 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 grzegorz/nyasync.py diff --git a/grzegorz/nyasync.py b/grzegorz/nyasync.py new file mode 100644 index 0000000..6d2de56 --- /dev/null +++ b/grzegorz/nyasync.py @@ -0,0 +1,48 @@ +import asyncio + +def ify(func): + """Decorate func to run async in default executor""" + asyncloop = asyncio.get_event_loop() + async def asyncified(*args, **kwargs): + return await asyncloop.run_in_executor( + None, lambda: func(*args, **kwargs)) + return asyncified + +class Queue(asyncio.Queue): + __anext__ = asyncio.Queue.get + + def __aiter__(self): + return self + +class Event: + def __init__(self): + self.monitor = asyncio.Condition() + + def __aiter__(self): + return self.monitor.wait() + + async def notify(self): + with await self.monitor: + self.monitor.notify_all() + +class Condition: + def __init__(self, predicate): + self.predicate = predicate + self.monitor = asyncio.Condition() + + def __aiter__(self): + return self.monitor.wait_for(self.predicate) + + async def notify(self): + with await self.monitor: + self.monitor.notify_all() + +class UnixConnection: + def __init__(self, path): + (self.reader, self.writer) = await asyncio.open_unix_connection(path) + + def __aiter__(self): + return self.reader.__aiter__() + + def write(self, data): + return self.writer.write(data);