Created
October 28, 2017 17:44
-
-
Save KiT106/52cd3cac8ce1aca9c2021e860f449163 to your computer and use it in GitHub Desktop.
generator vs. coroutines vs. async/await
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Reference: