Search code examples
pythonpython-3.xasynchronous

Using a coroutine as decorator


in this scenario:

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

@foo
async def boo(*args, **kwargs):
    pass

is the call to foo as a decorator for boo decorator an async call?

--First Edit: Also how does one handle calling chain of coroutines as decorators?


Solution

  • 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.