Using a coroutine as decorator

前端 未结 3 651
生来不讨喜
生来不讨喜 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:59

    Thanks to @blacknght's comment, considering

    def foo():
        def wrapper(func):
            @functools.wraps(func)
            async def wrapped(*args):
                 # Some fancy foo stuff
                return await func(*args)
            return wrapped
        return wrapper
    

    and

    def boo():
        def wrapper(func):
            @functools.wraps(func)
            async def wrapped(*args):
                # Some fancy boo stuff
                return await func(*args)
            return wrapped
        return wrapper
    

    as two decorators, and

    @foo()
    @boo()
    async def work(*args):
        pass
    

    As the foo is wrapping the work coroutine, the key is to await the func(*arg) in both decorators.

提交回复
热议问题