Skip to content

Instantly share code, notes, and snippets.

@johnssuh
Created July 4, 2018 09:24
Show Gist options
  • Select an option

  • Save johnssuh/d18c593fe4f8c0cdbab5ff53a6778e89 to your computer and use it in GitHub Desktop.

Select an option

Save johnssuh/d18c593fe4f8c0cdbab5ff53a6778e89 to your computer and use it in GitHub Desktop.
Some cool stuff with asyncio
import asyncio
class DummyAPI:
async def get(self, number):
print(f"GET {number} executed")
await asyncio.sleep(number)
return number, "a"
async def context_switched_get(self):
dispatch_list = []
for i in range(1,6):
dispatch_list.append(asyncio.ensure_future(self.get(i)))
await asyncio.sleep(0)
print("For context switched get, get is executed before this print statement")
done = await asyncio.gather(*dispatch_list, return_exceptions=True)
for e in done:
print(e)
async def gathered_get(self):
dispatch_list = []
for i in range(1,6):
dispatch_list.append(asyncio.ensure_future(self.get(i)))
print("For regular gathered get, get is executed after this print statement")
done = await asyncio.gather(*dispatch_list, return_exceptions=True)
for e in done:
print(e)
async def main(self):
await self.context_switched_get()
await self.gathered_get()
dummy = DummyAPI()
loop = asyncio.get_event_loop()
loop.run_until_complete(dummy.main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment