GitHub

Async Python: fire and forget method

27 Mar 2021 / Mihai Nueleanu

The decorator method

def fire_and_forget(f):
from functools import wraps

@wraps(f)
def wrapped(*args, **kwargs):
loop = asyncio.get_event_loop()
if callable(f):
return loop.run_in_executor(None, f, *args, **kwargs)
else:
raise TypeError('Task must be a callable')
return wrapped

An example:

Use the method above as a decorator for other methods:

@fire_and_forget
async hello_world():
sleep(5)
print("Successful")



python
async
fire and forget
background
method
function
Clap Claps

Comments

Hi, I'm Mihai

This is the place where I put stuff that I find interesting. Welcome to Dot.Method

GitHub Resume Contact Uses