Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 309
Juggernaut Avatar asked Feb 04 '17 17:02

Juggernaut


People also ask

Can decorators be async?

Not using async also gives the advantage of being able to use the same decorator in normal functions as well. The only advantage of having async with a single return await is to make it clearly documented the function must be awaited, but that doesn't matter in a decorator wrapper.

Is coroutine deprecated?

coroutine was also deprecated in python 3.7 and scheduled for removal in python 3.10. It already issues a deprecation warning if used.

When should I use coroutines Python?

Coroutines are generalizations of subroutines. They are used for cooperative multitasking where a process voluntarily yield (give away) control periodically or when idle in order to enable multiple applications to be run simultaneously.

What is Asyncio coroutine?

async def is a new syntax from Python 3.5. You could use await , async with and async for inside async def s. @coroutine is a functional analogue for async def but it works in Python 3.4+ and utilizes yield from construction instead of await . For practical perspective just never use @coroutine if your Python is 3.5+.


1 Answers

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.

like image 176
Juggernaut Avatar answered Sep 25 '22 20:09

Juggernaut