Decorating coroutines
Michele Simionato
michele.simionato at gmail.com
Sun Jul 16 00:58:15 EDT 2017
I have just released version 4.1.1 of the decorator module. The new feature is that it is possible to decorate coroutines. Here is an example of how
to define a decorator `log_start_stop` that can be used to trace coroutines:
$ cat x.py
import time
import logging
from asyncio import get_event_loop, sleep, wait
from decorator import decorator
@decorator
async def log_start_stop(coro, *args, **kwargs):
logging.info('Starting %s%s', coro.__name__, args)
t0 = time.time()
await coro(*args, **kwargs)
dt = time.time() - t0
logging.info('Ending %s%s after %d seconds', coro.__name__, args, dt)
@log_start_stop
async def task(n): # a do nothing task
for i in range(n):
await sleep(1)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
tasks = [task(3), task(2), task(1)]
get_event_loop().run_until_complete(wait(tasks))
This will print something like this:
~$ python3 x.py
INFO:root:Starting task(1,)
INFO:root:Starting task(3,)
INFO:root:Starting task(2,)
INFO:root:Ending task(1,) after 1 seconds
INFO:root:Ending task(2,) after 2 seconds
INFO:root:Ending task(3,) after 3 seconds
The trouble is that at work I am forced to maintain compatibility with Python 2.7, so I do not have significant code using coroutines. If there are people out there which use a lot of coroutines and would like to decorate them, I invite you to try out the decorator module and give me some feedback if you find errors or strange behaviors. I am not aware of any issues, but one is never sure with new features.
Thanks for your help,
Michele Simionato
More information about the Python-list
mailing list