In [2]:
Expand CodeCollapse Code
import asyncio

# This creates an event loop and indefinitely cycles through
# its collection of jobs.
# event_loop = asyncio.new_event_loop()
# event_loop.run_forever()
# jupyter notebook has already event loop running which will through error
In [4]:
Expand CodeCollapse Code
def hello_printer():
    print("hello")
In [5]:
Expand CodeCollapse Code
hello_printer()
hello
In [6]:
Expand CodeCollapse Code
async def hello_async_printer():
    print("hello async ")
In [7]:
Expand CodeCollapse Code
hello_async_printer()
Out[7]:
<coroutine object hello_async_printer at 0x7fb279f6af80>
In [18]:
Expand CodeCollapse Code
coroutine =hello_async_printer()
# This creates a Task object and schedules its execution via the event loop.
task = asyncio.create_task(coroutine)
hello async 
In [20]:
Expand CodeCollapse Code
await task
In [23]:
Expand CodeCollapse Code
import asyncio

async def coro_a():
   print("I am coro_a(). Hi!")

async def coro_b():
   print("I am coro_b(). I sure hope no one hogs the event loop...")

async def main():
   task_b = asyncio.create_task(coro_b())
   num_repeats = 3
   for _ in range(num_repeats):
      await coro_a()
   await task_b

await main() # should be asyncio.run(main())
I am coro_a(). Hi!
I am coro_a(). Hi!
I am coro_a(). Hi!
I am coro_b(). I sure hope no one hogs the event loop...
In [24]:
Expand CodeCollapse Code
async def main():
   task_b = asyncio.create_task(coro_b())
   num_repeats = 3
   for _ in range(num_repeats):
      await asyncio.create_task(coro_a())
   await task_b

await main() # should be asyncio.run(main())
I am coro_b(). I sure hope no one hogs the event loop...
I am coro_a(). Hi!
I am coro_a(). Hi!
I am coro_a(). Hi!
In [35]:
Expand CodeCollapse Code
async def main():
   task_b = asyncio.create_task(coro_b())
   num_repeats = 3
   for _ in range(num_repeats):
      print("Hello")
      await asyncio.create_task(coro_a())
   
   await task_b

await main() # should be asyncio.run(main())
Hello
I am coro_b(). I sure hope no one hogs the event loop...
I am coro_a(). Hi!
Hello
I am coro_a(). Hi!
Hello
I am coro_a(). Hi!
In [36]:
Expand CodeCollapse Code
class Rock:
    def __await__(self):
        value_sent_in = yield 7
        print(f"Rock.__await__ resuming with value: {value_sent_in}.")
        return value_sent_in

async def main():
    print("Beginning coroutine main().")
    rock = Rock()
    print("Awaiting rock...")
    value_from_rock = await rock
    print(f"Coroutine received value: {value_from_rock} from rock.")
    return 23

coroutine = main()
intermediate_result = coroutine.send(None)
print(f"Coroutine paused and returned intermediate value: {intermediate_result}.")

print(f"Resuming coroutine and sending in value: 42.")
try:
    coroutine.send(42)
except StopIteration as e:
    returned_value = e.value
print(f"Coroutine main() finished and provided value: {returned_value}.")
Beginning coroutine main().
Awaiting rock...
Coroutine paused and returned intermediate value: 7.
Resuming coroutine and sending in value: 42.
Rock.__await__ resuming with value: 42.
Coroutine received value: 42 from rock.
Coroutine main() finished and provided value: 23.
In [45]:
Expand CodeCollapse Code
import datetime, time
async def other_work():
    print("I like work. Work work.")

async def main():
    # Add a few other tasks to the event loop, so there's something
    # to do while asynchronously sleeping.
    work_tasks = [
        asyncio.create_task(other_work()),
        asyncio.create_task(other_work()),
        asyncio.create_task(other_work())
    ]
    print(
        "Beginning asynchronous sleep at time: "
        f"{datetime.datetime.now().strftime("%H:%M:%S")}."
    )
    await asyncio.create_task(async_sleep(3))
    print(
        "Done asynchronous sleep at time: "
        f"{datetime.datetime.now().strftime("%H:%M:%S")}."
    )
    # asyncio.gather effectively awaits each task in the collection.
    await asyncio.gather(*work_tasks)
await main()
Beginning asynchronous sleep at time: 16:27:22.
I like work. Work work.
I like work. Work work.
I like work. Work work.
Done asynchronous sleep at time: 16:27:25.
In [46]:
Expand CodeCollapse Code
async def async_sleep(seconds: float):
    future = asyncio.Future()
    time_to_wake = time.time() + seconds
    # Add the watcher-task to the event loop.
    watcher_task = asyncio.create_task(_sleep_watcher(future, time_to_wake))
    # Block until the future is marked as done.
    await future
await main()
Beginning asynchronous sleep at time: 16:27:54.
I like work. Work work.
I like work. Work work.
I like work. Work work.
Done asynchronous sleep at time: 16:27:57.
In [47]:
Expand CodeCollapse Code
class YieldToEventLoop:
    def __await__(self):
        yield

async def _sleep_watcher(future, time_to_wake):
    while True:
        if time.time() >= time_to_wake:
            # This marks the future as done.
            future.set_result(None)
            break
        else:
            await YieldToEventLoop()