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()
Coroutines can be scheduled in the eventloop (internally they are wrapped in a Task
).
The decorator is not necessary, but has several advantages:
yield
)
In [3]:
@asyncio.coroutine
def hello_world():
yield from asyncio.sleep(1.0)
print('Hello World!')
loop.run_until_complete(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()
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__'))
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
).