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

Hello,

I'm Mihai, the founder of dotmethod - a software development company based in 🇩🇰 Copenhagen.

GitHub Resume Contact Uses