Python异步并通过自定义EventLoop和自定义Future等待

时间:2019-09-11 11:08:01

标签: python python-3.x promise async-await

我试图查看Python的asyncawait是否可以帮助我简化回调链。我仍在用Python学习asyncawait

我有一个用于异步编程的现有接口类,以支持三个自定义实现。调用该接口看起来像这样:

def without_async(value):
    p = MyFuture(lambda x: x * 2).then(lambda y: str(y))
    p.evaluate(value)
    return p.result

assert without_async(2) == '4'

MyFutureasyncio.FuturePromises/A+中定义的接口非常相似:

class MyFuture(Generic[T]):
    def __init__(self, callback: Callable[[T], ...]=None):
        self.result: T = None
        self.callback = callback
        self._next: MyFuture = None

    def then(self, callback: Callable[[T], U]) -> MyFuture:
        # Similar to Future.add_done_callback
        self.callback = callback
        self._next = MyFuture()
        return self._next

    def evaluate(self, result: T):
        # similar to Future.set_result
        self.result = result
        self._next.evaluate(self.callback(self.result))

现在,有没有任何方法可以使用await使语法更漂亮?如果是,怎么办?

也许与此伪代码相似?

class MyFuture(collections.abc.Awaitable):
    def __await__(self): ...

def run_until_complete(future):
    ...

def wrap(x: T) -> MyFuture[T]:
    ...

async def with_async(value):
    x = 2 * await wrap(value)
    return str(await wrap(value))

assert run_until_complete(with_async(2)) == '4'

0 个答案:

没有答案