Skip to content

Instantly share code, notes, and snippets.

@KiT106
Created October 28, 2017 17:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KiT106/52cd3cac8ce1aca9c2021e860f449163 to your computer and use it in GitHub Desktop.
Save KiT106/52cd3cac8ce1aca9c2021e860f449163 to your computer and use it in GitHub Desktop.
generator vs. coroutines vs. async/await
import asyncio
async def compute(x, y):
print("Compute %s + %s ..." % (x, y))
await asyncio.sleep(1.0)
return x + y
async def print_sum(x, y):
result = await compute(x, y)
print("%s + %s = %s" % (x, y, result))
loop = asyncio.get_event_loop()
loop.run_until_complete(print_sum(1, 2))
loop.close()
import asyncio
@asyncio.coroutine
def compute(x, y):
print("Compute %s + %s ..." % (x, y))
yield from asyncio.sleep(1.0)
return x + y
@asyncio.coroutine
def print_sum(x, y):
result = yield from compute(x, y)
print("%s + %s = %s" % (x, y, result))
loop = asyncio.get_event_loop()
loop.run_until_complete(print_sum(1, 2))
loop.close()
def compute(x, y):
print("Compute %s + %s ..." % (x, y))
yield 1 # assume sleep 1 second
return x + y
def print_sum(x, y):
result = yield from compute(x, y)
print("%s + %s = %s" % (x, y, result))
try:
gens = print_sum(1, 2)
while True: # emulate event loop
next(gens)
except StopIteration:
print("Done")
def compute(x, y):
print("Compute %s + %s ..." % (x, y))
yield 1 # sleep 1 second
return x + y
def print_sum(x, y):
try:
gens = compute(x, y)
while True:
yield next(gens)
except StopIteration as e:
result = e.value
print("%s + %s = %s" % (x, y, result))
def main():
try:
gens = print_sum(1, 2)
while True:
next(gens)
except StopIteration:
print("Done")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment