Simple I/O Loop Examples for Python 3.4

Create an event loop (which automatically becomes the default event loop in the context).


In [1]:
import asyncio
loop = asyncio.get_event_loop()

Run a simple callback as soon as possible:


In [2]:
def hello_world():
    print('Hello World!')
    loop.stop()

loop.call_soon(hello_world)
loop.run_forever()


Hello World!

Coroutines can be scheduled in the eventloop (internally they are wrapped in a Task).

The decorator is not necessary, but has several advantages:

  • documents that this is a coroutine (instead of scanning the code for yield)
  • provides some debugging magic, to detect unscheduled coroutines

In [3]:
@asyncio.coroutine
def hello_world():
    yield from asyncio.sleep(1.0)
    print('Hello World!')

loop.run_until_complete(hello_world())


Hello World!

Interconnect a Future and a coroutine, and wrap a courotine in a Task (a subclass of Future).


In [1]:
@asyncio.coroutine
def slow_operation(future):
    yield from asyncio.sleep(1)
    future.set_result('Future is done!')

def got_result(future):
    print(future.result())
    loop.stop()
    
future = asyncio.Future()
future.add_done_callback(got_result)

# wrap the coro in a special Future (a Task) and schedule it
loop.create_task(slow_operation(future))
# could use asyncio.async, but this is deprecated

loop.run_forever()


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-02a280871274> in <module>()
----> 1 @asyncio.coroutine
      2 def slow_operation(future):
      3     yield from asyncio.sleep(1)
      4     future.set_result('Future is done!')
      5 

NameError: name 'asyncio' is not defined

Futures implement the coroutine interface, so they can be yielded from (yield from actually calls __iter__ before the iteration).


In [5]:
future = asyncio.Future()
print(hasattr(future, '__iter__'))


True

Internally the asyncio event loop works with Handle instances, which wrap callbacks. The Task class is used to schedule / step through courotines (via its _step method and using call_soon).