A coroutine is a generator that follows certain conventions. For documentation purposes, all coroutines should be decorated with @asyncio.coroutine, but this cannot be strictly enforced.
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:
Things a coroutine can do:
Calling a coroutine does not start its code running – it is just a generator, and the coroutine object returned by the call is really a generator object, which doesn’t do anything until you iterate over it. In the case of a coroutine object, there are two basic ways to start it running: call yield from coroutine from another coroutine (assuming the other coroutine is already running!), or schedule its execution using the async() function or the BaseEventLoop.create_task() method.
Coroutines (and tasks) can only run when the event loop is running.
Decorator to mark coroutines.
If the coroutine is not yielded from before it is destroyed, an error message is logged. See Detect coroutines never scheduled.
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 async().
Example of coroutine displaying "Hello World":
import asyncio @asyncio.coroutine 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()
Example of coroutine displaying the current date every second during 5 seconds using the sleep() function:
import asyncio import datetime @asyncio.coroutine def display_date(loop): end_time = loop.time() + 5.0 while True: print(datetime.datetime.now()) if (loop.time() + 1.0) >= end_time: break yield from 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()
Example chaining coroutines:
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()
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 BaseEventLoop.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 BaseEventLoop.call_later() to wake up the task in 1 second.
The operation is not allowed in this state.
The operation exceeded the given deadline.
This exception is different from the builtin TimeoutError exception!
This class is almost compatible with concurrent.futures.Future.
This class is not thread safe.
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.
Return True if the future was cancelled.
Return True if the future is done.
Done means either that a result / exception are available, or that the future was cancelled.
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.
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 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 all instances of a callback from the “call when done” list.
Returns the number of callbacks removed.
Mark the future done and set its result.
If the future is already done when this method is called, raises InvalidStateError.
import asyncio @asyncio.coroutine def slow_operation(future): yield from 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.
The previous example can be written differently using the Future.add_done_callback() method to describe explicitly the control flow:
import asyncio @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() 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.
A task is responsible for executing a coroutine object in an event loop. If the wrapped coroutine yields from a future, the task suspends the execution of the wrapped coroutine and waits for the completition of the future. When the future is done, the execution of the wrapped coroutine restarts with the result or the exception of the future.
Event loops use cooperative scheduling: an event loop only runs one task at a time. Other tasks may run in parallel if other event loops are running in different threads. While a task waits for the completion of a future, the event loop executes a new task.
The cancellation of a task is different from the cancelation of a future. Calling cancel() will throw a CancelledError to the wrapped coroutine. cancelled() only returns True if the wrapped coroutine did not catch the CancelledError exception, or raised a CancelledError exception.
This class is not thread safe.
Return a set of all tasks for an event loop.
By default all tasks for the current event loop are returned.
Return the currently running task in an event loop or None.
By default the current task for the current event loop is returned.
None is returned when called not in the context of a Task.
Request that this task cancel itself.
This arranges for a CancelledError to be thrown into the wrapped coroutine on the next cycle through the event loop. The coroutine then has a chance to clean up or even deny the request using try/except/finally.
Unlike Future.cancel(), this does not guarantee that the task will be cancelled: the exception might be caught and acted upon, delaying cancellation of the task or preventing cancellation completely. The task may also return a value or raise a different exception.
Immediately after this method is called, cancelled() will not return True (unless the task was already cancelled). A task will be marked as cancelled when the wrapped coroutine terminates with a CancelledError exception (even if cancel() was not called).
Return the list of stack frames for this task’s coroutine.
If the coroutine is not done, this returns the stack where it is suspended. If the coroutine has completed successfully or was cancelled, this returns an empty list. If the coroutine was terminated by an exception, this returns the list of traceback frames.
The frames are always ordered from oldest to newest.
The optional limit gives the maximum number of frames to return; by default all available frames are returned. Its meaning differs depending on whether a stack or a traceback is returned: the newest frames of a stack are returned, but the oldest frames of a traceback are returned. (This matches the behavior of the traceback module.)
For reasons beyond our control, only one stack frame is returned for a suspended coroutine.
Print the stack or traceback for this task’s coroutine.
This produces output similar to that of the traceback module, for the frames retrieved by get_stack(). The limit argument is passed to get_stack(). The file argument is an I/O stream to which the output is written; by default output is written to sys.stderr.
Example executing 3 tasks (A, B, C) in parallel:
import asyncio @asyncio.coroutine def factorial(name, number): f = 1 for i in range(2, number+1): print("Task %s: Compute factorial(%s)..." % (name, i)) yield from asyncio.sleep(1) f *= i print("Task %s: factorial(%s) = %s" % (name, number, f)) loop = asyncio.get_event_loop() tasks = [ asyncio.ensure_future(factorial("A", 2)), asyncio.ensure_future(factorial("B", 3)), asyncio.ensure_future(factorial("C", 4))] loop.run_until_complete(asyncio.wait(tasks)) loop.close()
Task A: Compute factorial(2)... Task B: Compute factorial(2)... Task C: Compute factorial(2)... Task A: factorial(2) = 2 Task B: Compute factorial(3)... Task C: Compute factorial(3)... Task B: factorial(3) = 6 Task C: Compute factorial(4)... Task C: factorial(4) = 24
A task is automatically scheduled for execution when it is created. The event loop stops when all tasks are done.
In the functions below, the optional loop argument allows to explicitly set the event loop object used by the underlying task or coroutine. If it’s not provided, the default event loop is used.
Return an iterator whose values, when waited for, are Future instances.
Raises asyncio.TimeoutError if the timeout occurs before all Futures are done.
for f in as_completed(fs): result = yield from f # The 'yield from' may raise # Use result
The futures f are not necessarily members of fs.
If the argument is a Future, it is returned directly.
New in version 3.4.4.
The BaseEventLoop.create_task() method.
A deprecated alias to ensure_future().
Deprecated since version 3.4.4.
Return a future aggregating results from the given coroutine objects or futures.
All futures must share the same event loop. If all the tasks are done successfully, the returned future’s result is the list of results (in the order of the original sequence, not necessarily the order of results arrival). If return_exceptions is True, exceptions in the tasks are treated the same as successful results, and gathered in the result list; otherwise, the first raised exception will be immediately propagated to the returned future.
Cancellation: if the outer Future is cancelled, all children (that have not completed yet) are also cancelled. If any child is cancelled, this is treated as if it raised CancelledError – the outer Future is not cancelled in this case. (This is to prevent the cancellation of one child to cause other children to be cancelled.)
Create a coroutine that completes after a given time (in seconds). If result is provided, it is produced to the caller when the coroutine completes.
The resolution of the sleep depends on the granularity of the event loop.
This function is a coroutine.
Wait for a future, shielding it from cancellation.
res = yield from shield(something())
is exactly equivalent to the statement:
res = yield from something()
except that if the coroutine containing it is cancelled, the task running in something() is not cancelled. From the point of view of something(), the cancellation did not happen. But its caller is still cancelled, so the yield-from expression still raises CancelledError. Note: If something() is cancelled by other means this will still cancel shield().
If you want to completely ignore cancellation (not recommended) you can combine shield() with a try/except clause, as follows:
try: res = yield from shield(something()) except CancelledError: res = None
Wait for the Futures and coroutine objects given by the sequence futures to complete. Coroutines will be wrapped in Tasks. Returns two sets of Future: (done, pending).
The sequence futures must not be empty.
timeout can be used to control the maximum number of seconds to wait before returning. timeout can be an int or float. If timeout is not specified or None, there is no limit to the wait time.
return_when indicates when this function should return. It must be one of the following constants of the concurrent.futures module:
|FIRST_COMPLETED||The function will return when any future finishes or is cancelled.|
|FIRST_EXCEPTION||The function will return when any future finishes by raising an exception. If no future raises an exception then it is equivalent to ALL_COMPLETED.|
|ALL_COMPLETED||The function will return when all futures finish or are cancelled.|
This function is a coroutine.
done, pending = yield from asyncio.wait(fs)
This does not raise asyncio.TimeoutError! Futures that aren’t done when the timeout occurs are returned in the second set.
Coroutine will be wrapped in Task.
If the wait is cancelled, the future fut is also cancelled.
This function is a coroutine, usage:
result = yield from asyncio.wait_for(fut, 60.0)
Changed in version 3.4.3: If the wait is cancelled, the future fut is now also cancelled.