Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jamesstidard
Last active September 30, 2016 00:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesstidard/3317969472f4b3fc938a4ab29c5e1ecf to your computer and use it in GitHub Desktop.
Save jamesstidard/3317969472f4b3fc938a4ab29c5e1ecf to your computer and use it in GitHub Desktop.
Optional asynchronous interface
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()
return loop.run_until_complete(f(*args, **kwargs))
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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment