Async Python

Asynchronous Python is a pleasant experience to work with.  Nothing unexpected or weird about using the await/async keywords and how they work.

Basic example of an asynchronous function

async def this_takes_awhile(wait_time_seconds=1):
    await asyncio.sleep(wait_time_seconds)

That's all it takes with the asyncio package.

Write a decorator to wrap up the execution time like so

import asyncio
import random
import time

def timeit(func):
    async def process(func, *args, **params):
        if asyncio.iscoroutinefunction(func):
            return await func(*args, **params)
        else:
            return func(*args, **params)

    async def helper(*args, **params):
        start = time.time()
        result = await process(func, *args, **params)
        print(f'Method: {func.__name__} Time: {time.time() - start}')
        return result
    return helper

Now call it like so

@timeit
async def this_takes_awhile(wait_time_seconds=1):
    await asyncio.sleep(wait_time_seconds)

def random_number(min=1, max=10):
    if min > max:
        raise Exception(f'Minimum value {min} is greater than {max}')
    number_generator = random.Random()
    return number_generator.randint(min, max)
    
if __name__ == '__main__':
    asyncio.run(this_takes_awhile(random_number()))

Results

C:\projects\templates\venv\Scripts\python.exe C:/projects/templates/main.py
Method: this_takes_awhile Time: 9.008285999298096