18.5.3.1. Coroutines
Coroutines used with asyncio may be implemented using the
async def statement, or by using generators.
The async def type of coroutine was added in Python 3.5, and
is recommended if there is no need to support older Python versions.
Generator-based coroutines should be decorated with @asyncio.coroutine, although this is not strictly enforced.
The decorator enables compatibility with async def coroutines,
and also serves as documentation. Generator-based
coroutines use the yield from syntax introduced in PEP 380,
instead of the original yield syntax.
The word “coroutine”, like the word “generator”, is used for two
different (though related) concepts:
- The function that defines a coroutine
(a function definition using
async def or
decorated with @asyncio.coroutine). If disambiguation is needed
we will call this a coroutine function (iscoroutinefunction()
returns True).
- The object obtained by calling a coroutine function. This object
represents a computation or an I/O operation (usually a combination)
that will complete eventually. If disambiguation is needed we will
call it a coroutine object (
iscoroutine() returns True).
Things a coroutine can do:
result = await future or result = yield from future –
suspends the coroutine until the
future is done, then returns the future’s result, or raises an
exception, which will be propagated. (If the future is cancelled,
it will raise a CancelledError exception.) Note that tasks are
futures, and everything said about futures also applies to tasks.
result = await coroutine or result = yield from coroutine –
wait for another coroutine to
produce a result (or raise an exception, which will be propagated).
The coroutine expression must be a call to another coroutine.
return expression – produce a result to the coroutine that is
waiting for this one using await or yield from.
raise exception – raise an exception in the coroutine that is
waiting for this one using await or yield from.
Calling a coroutine does not start its code running –
the coroutine object returned by the call doesn’t do anything until you
schedule its execution. There are two basic ways to start it running:
call await coroutine or yield from coroutine from another coroutine
(assuming the other coroutine is already running!), or schedule its execution
using the ensure_future() function or the AbstractEventLoop.create_task()
method.
Coroutines (and tasks) can only run when the event loop is running.
-
@asyncio.coroutine
Decorator to mark generator-based coroutines. This enables
the generator use yield from to call async
def coroutines, and also enables the generator to be called by
async def coroutines, for instance using an
await expression.
There is no need to decorate async def coroutines themselves.
If the generator is not yielded from before it is destroyed, an error
message is logged. See Detect coroutines never scheduled.
Note
In this documentation, some methods are documented as coroutines,
even if they are plain Python functions returning a Future.
This is intentional to have a freedom of tweaking the implementation
of these functions in the future. If such a function is needed to be
used in a callback-style code, wrap its result with ensure_future().
18.5.3.1.1. Example: Hello World coroutine
Example of coroutine displaying "Hello World":
import asyncio
async def hello_world():
print("Hello World!")
loop = asyncio.get_event_loop()
# Blocking call which returns when the hello_world() coroutine is done
loop.run_until_complete(hello_world())
loop.close()
18.5.3.1.2. Example: Coroutine displaying the current date
Example of coroutine displaying the current date every second during 5 seconds
using the sleep() function:
import asyncio
import datetime
async def display_date(loop):
end_time = loop.time() + 5.0
while True:
print(datetime.datetime.now())
if (loop.time() + 1.0) >= end_time:
break
await asyncio.sleep(1)
loop = asyncio.get_event_loop()
# Blocking call which returns when the display_date() coroutine is done
loop.run_until_complete(display_date(loop))
loop.close()
18.5.3.1.3. Example: Chain coroutines
Example chaining coroutines:
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()
compute() is chained to print_sum(): print_sum() coroutine waits
until compute() is completed before returning its result.
Sequence diagram of the example:
The “Task” is created by the AbstractEventLoop.run_until_complete() method
when it gets a coroutine object instead of a task.
The diagram shows the control flow, it does not describe exactly how things
work internally. For example, the sleep coroutine creates an internal future
which uses AbstractEventLoop.call_later() to wake up the task in 1 second.
18.5.3.4. Future
-
class
asyncio.Future(*, loop=None)
This class is almost compatible with concurrent.futures.Future.
Differences:
This class is not thread safe.
-
cancel()
Cancel the future and schedule callbacks.
If the future is already done or cancelled, return False. Otherwise,
change the future’s state to cancelled, schedule the callbacks and return
True.
-
cancelled()
Return True if the future was cancelled.
-
done()
Return True if the future is done.
Done means either that a result / exception are available, or that the
future was cancelled.
-
result()
Return the result this future represents.
If the future has been cancelled, raises CancelledError. If the
future’s result isn’t yet available, raises InvalidStateError. If
the future is done and has an exception set, this exception is raised.
-
exception()
Return the exception that was set on this future.
The exception (or None if no exception was set) is returned only if
the future is done. If the future has been cancelled, raises
CancelledError. If the future isn’t done yet, raises
InvalidStateError.
-
add_done_callback(fn)
Add a callback to be run when the future becomes done.
The callback is called with a single argument - the future object. If the
future is already done when this is called, the callback is scheduled
with call_soon().
Use functools.partial to pass parameters to the callback. For example,
fut.add_done_callback(functools.partial(print, "Future:",
flush=True)) will call print("Future:", fut, flush=True).
-
remove_done_callback(fn)
Remove all instances of a callback from the “call when done” list.
Returns the number of callbacks removed.
-
set_result(result)
Mark the future done and set its result.
If the future is already done when this method is called, raises
InvalidStateError.
-
set_exception(exception)
Mark the future done and set an exception.
If the future is already done when this method is called, raises
InvalidStateError.
18.5.3.4.1. Example: Future with run_until_complete()
Example combining a Future and a coroutine function:
import asyncio
async def slow_operation(future):
await asyncio.sleep(1)
future.set_result('Future is done!')
loop = asyncio.get_event_loop()
future = asyncio.Future()
asyncio.ensure_future(slow_operation(future))
loop.run_until_complete(future)
print(future.result())
loop.close()
The coroutine function is responsible for the computation (which takes 1 second)
and it stores the result into the future. The
run_until_complete() method waits for the completion of
the future.
18.5.3.4.2. Example: Future with run_forever()
The previous example can be written differently using the
Future.add_done_callback() method to describe explicitly the control
flow:
import asyncio
async def slow_operation(future):
await asyncio.sleep(1)
future.set_result('Future is done!')
def got_result(future):
print(future.result())
loop.stop()
loop = asyncio.get_event_loop()
future = asyncio.Future()
asyncio.ensure_future(slow_operation(future))
future.add_done_callback(got_result)
try:
loop.run_forever()
finally:
loop.close()
In this example, the future is used to link slow_operation() to
got_result(): when slow_operation() is done, got_result() is called
with the result.