Using a coroutine as decorator

前端 未结 3 654
生来不讨喜
生来不讨喜 2021-02-03 23:33

in this scenario:

async def foo(f):
    async def wrapper(*args, **kwargs):
        return f(*args, **kwargs)
    return wrapper

@foo
async def boo(*args, **kwa         


        
3条回答
  •  遇见更好的自我
    2021-02-03 23:58

    Here is an alternate approach using the decorator library (i.e. pip install decorator first):

    import asyncio
    
    import decorator
    
    
    @decorator.decorator
    async def decorate_coro(coro, *args, **kwargs):
        try:
            res = await coro(*args, **kwargs)
        except Exception as e:
            print(e)
        else:
            print(res)
    
    
    @decorate_coro
    async def f():
        return 42
    
    
    @decorate_coro
    async def g():
        return 1 / 0
    
    
    async def main():
        return await asyncio.gather(f(), g())
    
    if __name__ == '__main__':
        asyncio.run(main())
    

    Output:

    42
    division by zero
    

提交回复
热议问题