Coroutines and Tasks

This section outlines high-level asyncio APIs to work with coroutinesand Tasks.

Coroutines

Coroutines declared with async/await syntax is the preferred way ofwriting asyncio applications. For example, the following snippetof code (requires Python 3.7+) prints “hello”, waits 1 second,and then prints “world”:

>>>importasyncio>>>asyncdefmain():...print('hello')...awaitasyncio.sleep(1)...print('world')>>>asyncio.run(main())helloworld

Note that simply calling a coroutine will not schedule it tobe executed:

>>>main()<coroutine object main at 0x1053bb7c8>

To actually run a coroutine, asyncio provides three main mechanisms:

  • Theasyncio.run() function to run the top-levelentry point “main()” function (see the above example.)

  • Awaiting on a coroutine. The following snippet of code willprint “hello” after waiting for 1 second, and then print “world”after waiting foranother 2 seconds:

    importasyncioimporttimeasyncdefsay_after(delay,what):awaitasyncio.sleep(delay)print(what)asyncdefmain():print(f"started at{time.strftime('%X')}")awaitsay_after(1,'hello')awaitsay_after(2,'world')print(f"finished at{time.strftime('%X')}")asyncio.run(main())

    Expected output:

    startedat17:13:52helloworldfinishedat17:13:55
  • Theasyncio.create_task() function to run coroutinesconcurrently as asyncioTasks.

    Let’s modify the above example and run twosay_after coroutinesconcurrently:

    asyncdefmain():task1=asyncio.create_task(say_after(1,'hello'))task2=asyncio.create_task(say_after(2,'world'))print(f"started at{time.strftime('%X')}")# Wait until both tasks are completed (should take# around 2 seconds.)awaittask1awaittask2print(f"finished at{time.strftime('%X')}")

    Note that expected output now shows that the snippet runs1 second faster than before:

    startedat17:14:32helloworldfinishedat17:14:34

Awaitables

We say that an object is anawaitable object if it can be usedin anawait expression. Many asyncio APIs are designed toaccept awaitables.

There are three main types ofawaitable objects:coroutines,Tasks, andFutures.

Coroutines

Python coroutines areawaitables and therefore can be awaited fromother coroutines:

importasyncioasyncdefnested():return42asyncdefmain():# Nothing happens if we just call "nested()".# A coroutine object is created but not awaited,# so it *won't run at all*.nested()# Let's do it differently now and await it:print(awaitnested())# will print "42".asyncio.run(main())

Important

In this documentation the term “coroutine” can be used fortwo closely related concepts:

  • acoroutine function: anasyncdef function;

  • acoroutine object: an object returned by calling acoroutine function.

asyncio also supports legacygenerator-based coroutines.

Tasks

Tasks are used to schedule coroutinesconcurrently.

When a coroutine is wrapped into aTask with functions likeasyncio.create_task() the coroutine is automaticallyscheduled to run soon:

importasyncioasyncdefnested():return42asyncdefmain():# Schedule nested() to run soon concurrently# with "main()".task=asyncio.create_task(nested())# "task" can now be used to cancel "nested()", or# can simply be awaited to wait until it is complete:awaittaskasyncio.run(main())

Futures

AFuture is a speciallow-level awaitable object thatrepresents aneventual result of an asynchronous operation.

When a Future object isawaited it means that the coroutine willwait until the Future is resolved in some other place.

Future objects in asyncio are needed to allow callback-based codeto be used with async/await.

Normallythere is no need to create Future objects at theapplication level code.

Future objects, sometimes exposed by libraries and some asyncioAPIs, can be awaited:

asyncdefmain():awaitfunction_that_returns_a_future_object()# this is also valid:awaitasyncio.gather(function_that_returns_a_future_object(),some_python_coroutine())

A good example of a low-level function that returns a Future objectisloop.run_in_executor().

Running an asyncio Program

asyncio.run(coro,*,debug=False)

Execute thecoroutinecoro and return the result.

This function runs the passed coroutine, taking care ofmanaging the asyncio event loop andfinalizing asynchronousgenerators.

This function cannot be called when another asyncio event loop isrunning in the same thread.

Ifdebug isTrue, the event loop will be run in debug mode.

This function always creates a new event loop and closes it atthe end. It should be used as a main entry point for asyncioprograms, and should ideally only be called once.

Example:

asyncdefmain():awaitasyncio.sleep(1)print('hello')asyncio.run(main())

New in version 3.7:Important: this function has been added to asyncio inPython 3.7 on aprovisional basis.

Creating Tasks

asyncio.create_task(coro)

Wrap thecorocoroutine into aTaskand schedule its execution. Return the Task object.

The task is executed in the loop returned byget_running_loop(),RuntimeError is raised if there is no running loop incurrent thread.

This function has beenadded in Python 3.7. Prior toPython 3.7, the low-levelasyncio.ensure_future() functioncan be used instead:

asyncdefcoro():...# In Python 3.7+task=asyncio.create_task(coro())...# This works in all Python versions but is less readabletask=asyncio.ensure_future(coro())...

New in version 3.7.

Sleeping

coroutineasyncio.sleep(delay,result=None,*,loop=None)

Block fordelay seconds.

Ifresult is provided, it is returned to the callerwhen the coroutine completes.

sleep() always suspends the current task, allowing other tasksto run.

Theloop argument is deprecated and scheduled for removalin Python 3.10.

Example of coroutine displaying the current date every secondfor 5 seconds:

importasyncioimportdatetimeasyncdefdisplay_date():loop=asyncio.get_running_loop()end_time=loop.time()+5.0whileTrue:print(datetime.datetime.now())if(loop.time()+1.0)>=end_time:breakawaitasyncio.sleep(1)asyncio.run(display_date())

Running Tasks Concurrently

awaitableasyncio.gather(*aws,loop=None,return_exceptions=False)

Runawaitable objects in theawssequenceconcurrently.

If any awaitable inaws is a coroutine, it is automaticallyscheduled as a Task.

If all awaitables are completed successfully, the result is anaggregate list of returned values. The order of result valuescorresponds to the order of awaitables inaws.

Ifreturn_exceptions isFalse (default), the firstraised exception is immediately propagated to the task thatawaits ongather(). Other awaitables in theaws sequencewon’t be cancelled and will continue to run.

Ifreturn_exceptions isTrue, exceptions are treated thesame as successful results, and aggregated in the result list.

Ifgather() iscancelled, all submitted awaitables(that have not completed yet) are alsocancelled.

If any Task or Future from theaws sequence iscancelled, it istreated as if it raisedCancelledError – thegather()call isnot cancelled in this case. This is to prevent thecancellation of one submitted Task/Future to cause otherTasks/Futures to be cancelled.

Example:

importasyncioasyncdeffactorial(name,number):f=1foriinrange(2,number+1):print(f"Task{name}: Compute factorial({i})...")awaitasyncio.sleep(1)f*=iprint(f"Task{name}: factorial({number}) ={f}")asyncdefmain():# Schedule three calls *concurrently*:awaitasyncio.gather(factorial("A",2),factorial("B",3),factorial("C",4),)asyncio.run(main())# Expected output:##     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

Changed in version 3.7:If thegather itself is cancelled, the cancellation ispropagated regardless ofreturn_exceptions.

Shielding From Cancellation

awaitableasyncio.shield(aw,*,loop=None)

Protect anawaitable objectfrom beingcancelled.

Ifaw is a coroutine it is automatically scheduled as a Task.

The statement:

res=awaitshield(something())

is equivalent to:

res=awaitsomething()

except that if the coroutine containing it is cancelled, theTask running insomething() is not cancelled. From the pointof view ofsomething(), the cancellation did not happen.Although its caller is still cancelled, so the “await” expressionstill raises aCancelledError.

Ifsomething() is cancelled by other means (i.e. from withinitself) that would also cancelshield().

If it is desired to completely ignore cancellation (not recommended)theshield() function should be combined with a try/exceptclause, as follows:

try:res=awaitshield(something())exceptCancelledError:res=None

Timeouts

coroutineasyncio.wait_for(aw,timeout,*,loop=None)

Wait for theawawaitableto complete with a timeout.

Ifaw is a coroutine it is automatically scheduled as a Task.

timeout can either beNone or a float or int number of secondsto wait for. Iftimeout isNone, block until the futurecompletes.

If a timeout occurs, it cancels the task and raisesasyncio.TimeoutError.

To avoid the taskcancellation,wrap it inshield().

The function will wait until the future is actually cancelled,so the total wait time may exceed thetimeout.

If the wait is cancelled, the futureaw is also cancelled.

Theloop argument is deprecated and scheduled for removalin Python 3.10.

Example:

asyncdefeternity():# Sleep for one hourawaitasyncio.sleep(3600)print('yay!')asyncdefmain():# Wait for at most 1 secondtry:awaitasyncio.wait_for(eternity(),timeout=1.0)exceptasyncio.TimeoutError:print('timeout!')asyncio.run(main())# Expected output:##     timeout!

Changed in version 3.7:Whenaw is cancelled due to a timeout,wait_for waitsforaw to be cancelled. Previously, it raisedasyncio.TimeoutError immediately.

Waiting Primitives

coroutineasyncio.wait(aws,*,loop=None,timeout=None,return_when=ALL_COMPLETED)

Runawaitable objects in theawsset concurrently and block until the condition specifiedbyreturn_when.

If any awaitable inaws is a coroutine, it is automaticallyscheduled as a Task. Passing coroutines objects towait() directly is deprecated as it leads toconfusing behavior.

Returns two sets of Tasks/Futures:(done,pending).

Usage:

done,pending=awaitasyncio.wait(aws)

Theloop argument is deprecated and scheduled for removalin Python 3.10.

timeout (a float or int), if specified, can be used to controlthe maximum number of seconds to wait before returning.

Note that this function does not raiseasyncio.TimeoutError.Futures or Tasks that aren’t done when the timeout occurs are simplyreturned in the second set.

return_when indicates when this function should return. It mustbe one of the following constants:

Constant

Description

FIRST_COMPLETED

The function will return when anyfuture finishes or is cancelled.

FIRST_EXCEPTION

The function will return when anyfuture finishes by raising anexception. If no future raises anexception then it is equivalent toALL_COMPLETED.

ALL_COMPLETED

The function will return when allfutures finish or are cancelled.

Unlikewait_for(),wait() does not cancel thefutures when a timeout occurs.

Note

wait() schedules coroutines as Tasks automatically and laterreturns those implicitly created Task objects in(done,pending)sets. Therefore the following code won’t work as expected:

asyncdeffoo():return42coro=foo()done,pending=awaitasyncio.wait({coro})ifcoroindone:# This branch will never be run!

Here is how the above snippet can be fixed:

asyncdeffoo():return42task=asyncio.create_task(foo())done,pending=awaitasyncio.wait({task})iftaskindone:# Everything will work as expected now.

Passing coroutine objects towait() directly isdeprecated.

asyncio.as_completed(aws,*,loop=None,timeout=None)

Runawaitable objects in theawsset concurrently. Return an iterator ofFuture objects.Each Future object returned represents the earliest resultfrom the set of the remaining awaitables.

Raisesasyncio.TimeoutError if the timeout occurs beforeall Futures are done.

Example:

forfinas_completed(aws):earliest_result=awaitf# ...

Scheduling From Other Threads

asyncio.run_coroutine_threadsafe(coro,loop)

Submit a coroutine to the given event loop. Thread-safe.

Return aconcurrent.futures.Future to wait for the resultfrom another OS thread.

This function is meant to be called from a different OS threadthan the one where the event loop is running. Example:

# Create a coroutinecoro=asyncio.sleep(1,result=3)# Submit the coroutine to a given loopfuture=asyncio.run_coroutine_threadsafe(coro,loop)# Wait for the result with an optional timeout argumentassertfuture.result(timeout)==3

If an exception is raised in the coroutine, the returned Futurewill be notified. It can also be used to cancel the task inthe event loop:

try:result=future.result(timeout)exceptasyncio.TimeoutError:print('The coroutine took too long, cancelling the task...')future.cancel()exceptExceptionasexc:print(f'The coroutine raised an exception:{exc!r}')else:print(f'The coroutine returned:{result!r}')

See theconcurrency and multithreadingsection of the documentation.

Unlike other asyncio functions this function requires theloopargument to be passed explicitly.

New in version 3.5.1.

Introspection

asyncio.current_task(loop=None)

Return the currently runningTask instance, orNone ifno task is running.

Ifloop isNoneget_running_loop() is used to getthe current loop.

New in version 3.7.

asyncio.all_tasks(loop=None)

Return a set of not yet finishedTask objects run bythe loop.

Ifloop isNone,get_running_loop() is used for gettingcurrent loop.

New in version 3.7.

Task Object

classasyncio.Task(coro,*,loop=None)

AFuture-like object that runs a Pythoncoroutine. Not thread-safe.

Tasks are used to run coroutines in event loops.If a coroutine awaits on a Future, the Task suspendsthe execution of the coroutine and waits for the completionof the Future. When the Future isdone, the execution ofthe wrapped coroutine resumes.

Event loops use cooperative scheduling: an event loop runsone Task at a time. While a Task awaits for the completion of aFuture, the event loop runs other Tasks, callbacks, or performsIO operations.

Use the high-levelasyncio.create_task() function to createTasks, or the low-levelloop.create_task() orensure_future() functions. Manual instantiation of Tasksis discouraged.

To cancel a running Task use thecancel() method. Calling itwill cause the Task to throw aCancelledError exception intothe wrapped coroutine. If a coroutine is awaiting on a Futureobject during cancellation, the Future object will be cancelled.

cancelled() can be used to check if the Task was cancelled.The method returnsTrue if the wrapped coroutine did notsuppress theCancelledError exception and was actuallycancelled.

asyncio.Task inherits fromFuture all of itsAPIs exceptFuture.set_result() andFuture.set_exception().

Tasks support thecontextvars module. When a Taskis created it copies the current context and later runs itscoroutine in the copied context.

Changed in version 3.7:Added support for thecontextvars module.

cancel()

Request the Task to be cancelled.

This arranges for aCancelledError exception to be throwninto the wrapped coroutine on the next cycle of the event loop.

The coroutine then has a chance to clean up or even deny therequest by suppressing the exception with atry ……exceptCancelledErrorfinally block.Therefore, unlikeFuture.cancel(),Task.cancel() doesnot guarantee that the Task will be cancelled, althoughsuppressing cancellation completely is not common and is activelydiscouraged.

The following example illustrates how coroutines can interceptthe cancellation request:

asyncdefcancel_me():print('cancel_me(): before sleep')try:# Wait for 1 hourawaitasyncio.sleep(3600)exceptasyncio.CancelledError:print('cancel_me(): cancel sleep')raisefinally:print('cancel_me(): after sleep')asyncdefmain():# Create a "cancel_me" Tasktask=asyncio.create_task(cancel_me())# Wait for 1 secondawaitasyncio.sleep(1)task.cancel()try:awaittaskexceptasyncio.CancelledError:print("main(): cancel_me is cancelled now")asyncio.run(main())# Expected output:##     cancel_me(): before sleep#     cancel_me(): cancel sleep#     cancel_me(): after sleep#     main(): cancel_me is cancelled now
cancelled()

ReturnTrue if the Task iscancelled.

The Task iscancelled when the cancellation was requested withcancel() and the wrapped coroutine propagated theCancelledError exception thrown into it.

done()

ReturnTrue if the Task isdone.

A Task isdone when the wrapped coroutine either returneda value, raised an exception, or the Task was cancelled.

result()

Return the result of the Task.

If the Task isdone, the result of the wrapped coroutineis returned (or if the coroutine raised an exception, thatexception is re-raised.)

If the Task has beencancelled, this method raisesaCancelledError exception.

If the Task’s result isn’t yet available, this method raisesaInvalidStateError exception.

exception()

Return the exception of the Task.

If the wrapped coroutine raised an exception that exceptionis returned. If the wrapped coroutine returned normallythis method returnsNone.

If the Task has beencancelled, this method raises aCancelledError exception.

If the Task isn’tdone yet, this method raises anInvalidStateError exception.

add_done_callback(callback,*,context=None)

Add a callback to be run when the Task isdone.

This method should only be used in low-level callback-based code.

See the documentation ofFuture.add_done_callback()for more details.

remove_done_callback(callback)

Removecallback from the callbacks list.

This method should only be used in low-level callback-based code.

See the documentation ofFuture.remove_done_callback()for more details.

get_stack(*,limit=None)

Return the list of stack frames for this Task.

If the wrapped coroutine is not done, this returns the stackwhere it is suspended. If the coroutine has completedsuccessfully or was cancelled, this returns an empty list.If the coroutine was terminated by an exception, this returnsthe list of traceback frames.

The frames are always ordered from oldest to newest.

Only one stack frame is returned for a suspended coroutine.

The optionallimit argument sets the maximum number of framesto return; by default all available frames are returned.The ordering of the returned list differs depending on whethera stack or a traceback is returned: the newest frames of astack are returned, but the oldest frames of a traceback arereturned. (This matches the behavior of the traceback module.)

print_stack(*,limit=None,file=None)

Print the stack or traceback for this Task.

This produces output similar to that of the traceback modulefor the frames retrieved byget_stack().

Thelimit argument is passed toget_stack() directly.

Thefile argument is an I/O stream to which the outputis written; by default output is written tosys.stderr.

classmethodall_tasks(loop=None)

Return a set of all tasks for an event loop.

By default all tasks for the current event loop are returned.Ifloop isNone, theget_event_loop() functionis used to get the current loop.

This method isdeprecated and will be removed inPython 3.9. Use theasyncio.all_tasks() function instead.

classmethodcurrent_task(loop=None)

Return the currently running task orNone.

Ifloop isNone, theget_event_loop() functionis used to get the current loop.

This method isdeprecated and will be removed inPython 3.9. Use theasyncio.current_task() functioninstead.

Generator-based Coroutines

Note

Support for generator-based coroutines isdeprecated andis scheduled for removal in Python 3.10.

Generator-based coroutines predate async/await syntax. They arePython generators that useyieldfrom expressions to awaiton Futures and other coroutines.

Generator-based coroutines should be decorated with@asyncio.coroutine, although this is notenforced.

@asyncio.coroutine

Decorator to mark generator-based coroutines.

This decorator enables legacy generator-based coroutines to becompatible with async/await code:

@asyncio.coroutinedefold_style_coroutine():yield fromasyncio.sleep(1)asyncdefmain():awaitold_style_coroutine()

This decorator isdeprecated and is scheduled for removal inPython 3.10.

This decorator should not be used forasyncdefcoroutines.

asyncio.iscoroutine(obj)

ReturnTrue ifobj is acoroutine object.

This method is different frominspect.iscoroutine() becauseit returnsTrue for generator-based coroutines.

asyncio.iscoroutinefunction(func)

ReturnTrue iffunc is acoroutine function.

This method is different frominspect.iscoroutinefunction()because it returnsTrue for generator-based coroutine functionsdecorated with@coroutine.