How can I periodically execute a function with asyncio?

For Python versions below 3.5: import asyncio @asyncio.coroutine def periodic(): while True: print(‘periodic’) yield from asyncio.sleep(1) def stop(): task.cancel() loop = asyncio.get_event_loop() loop.call_later(5, stop) task = loop.create_task(periodic()) try: loop.run_until_complete(task) except asyncio.CancelledError: pass For Python 3.5 and above: import asyncio async def periodic(): while True: print(‘periodic’) await asyncio.sleep(1) def stop(): task.cancel() loop = asyncio.get_event_loop() loop.call_later(5, stop) … Read more

What is the ‘@=’ symbol for in Python?

From the documentation: The @ (at) operator is intended to be used for matrix multiplication. No builtin Python types implement this operator. The @ operator was introduced in Python 3.5. @= is matrix multiplication followed by assignment, as you would expect. They map to __matmul__, __rmatmul__ or __imatmul__ similar to how + and += map … Read more

“Fire and forget” python async/await

Upd: Replace asyncio.ensure_future with asyncio.create_task everywhere if you’re using Python >= 3.7 It’s a newer, nicer way to spawn tasks. asyncio.Task to “fire and forget” According to python docs for asyncio.Task it is possible to start some coroutine to execute “in the background”. The task created by asyncio.ensure_future won’t block the execution (therefore the function … Read more