import asyncio
from functools import wraps


def serializable(f):
    @wraps(f)
    def wrapper(*args, asynchronous=False, **kwargs):
        if asynchronous:
            return f(*args, **kwargs)
        else:
            # Get pythons current execution thread and use that
            loop   = asyncio.get_event_loop()
            result = loop.run_until_complete(f(*args, **kwargs))
            return result
    return wrapper


@serializable
async def my_function(period):
    await asyncio.sleep(period)
    return 'my_function complete'


print('Calling function synchronouly...')
result = my_function(5, asynchronous=False)
print(result)


async def call_it_async():
    print('Calling function asynchronouly...')
    result = await my_function(5, asynchronous=True)
    print(result)


# Counter to prove to myself it's a coroutine
async def counter():
    print('Starting counter coroutine...')
    count = 1
    while count <= 10:
        print(count)
        await asyncio.sleep(1)
        count = count + 1


loop = asyncio.get_event_loop()
tasks = [
    asyncio.ensure_future(call_it_async()),
    asyncio.ensure_future(counter())]
loop.run_until_complete(asyncio.gather(*tasks))
loop.close()
