How can I await inside future-like object's __await__?

后端 未结 6 2100
天命终不由人
天命终不由人 2020-12-02 17:02

PEP 0492 adds new __await__ magic method. Object that implements this method becomes future-like object and can be awaited using await. It

6条回答
  •  不知归路
    2020-12-02 17:29

    Use a decorator.

    def chain__await__(f):
        return lambda *args, **kwargs: f(*args, **kwargs).__await__()
    

    Then write __await__ as a native coroutine.

    async def new_sleep():
        await asyncio.sleep(2)
    
    class Waiting:
        @chain__await__
        async def __await__(self):
            return await new_sleep()
    

提交回复
热议问题