コルーチンと Task

この節では、コルーチンと Task を利用する高レベルの asyncio の API の概略を解説します。

コルーチン

Source code:Lib/asyncio/coroutines.py


async/await 構文で宣言されたコルーチン は、 asyncio を使ったアプリケーションを書くのに推奨される方法です。例えば、次のコードスニペットは "hello" を出力し、そこから 1 秒待って "world" を出力します:

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

単にコルーチンを呼び出しただけでは、コルーチンの実行スケジュールは予約されていないことに注意してください:

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

実際にコルーチンを実行するために、asyncio は以下のメカニズムを提供しています:

  • 最上位のエントリーポイントである "main()" 関数を実行するasyncio.run() 関数 (上の例を参照してください。)

  • コルーチンを await すること。次のコード片は 1 秒間待機した後に "hello" と出力し、更に 2 秒間待機してから "world" と出力します:

    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())

    予想される出力:

    startedat17:13:52helloworldfinishedat17:13:55
  • asyncio のTasks としてコルーチンを並行して走らせるasyncio.create_task() 関数。

    上のコード例を編集して、ふたつのsay_after コルーチンを並行して 走らせてみましょう:

    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')}")

    予想される出力が、スニペットの実行が前回よりも 1 秒早いことを示していることに注意してください:

    startedat17:14:32helloworldfinishedat17:14:34
  • Theasyncio.TaskGroup class provides a more modernalternative tocreate_task().Using this API, the last example becomes:

    asyncdefmain():asyncwithasyncio.TaskGroup()astg:task1=tg.create_task(say_after(1,'hello'))task2=tg.create_task(say_after(2,'world'))print(f"started at{time.strftime('%X')}")# The await is implicit when the context manager exits.print(f"finished at{time.strftime('%X')}")

    The timing and output should be the same as for the previous version.

    Added in version 3.11:asyncio.TaskGroup.

Awaitable

あるオブジェクトをawait 式の中で使うことができる場合、そのオブジェクトをawaitable オブジェクトと言います。多くの asyncio API は awaitable を受け取るように設計されています。

awaitable オブジェクトには主に3つの種類があります:コルーチン,Task, そしてFuture です

コルーチン

Python のコルーチンはawaitable であり、他のコルーチンから待機されることができます:

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()# will raise a "RuntimeWarning".# Let's do it differently now and await it:print(awaitnested())# will print "42".asyncio.run(main())

重要

このドキュメントにおいて「コルーチン」という用語は以下2つの密接に関連した概念に対して使用できます:

  • コルーチン関数:asyncdef 関数;

  • コルーチンオブジェクト:コルーチン関数 を呼び出すと返ってくるオブジェクト.

Task

Task は、コルーチンを並行に スケジュールするのに使います。

asyncio.create_task() のような関数で、コルーチンがTask にラップされているとき、自動的にコルーチンは即時実行されるようにスケジュールされます:

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())

Future

Future は、非同期処理の最終結果 を表現する特別な低レベルの awaitable オブジェクトです。

Future オブジェクトが待機 (await) されている とは、Future がどこか他の場所で解決されるまでコルーチンが待機するということです。

asyncioのFutureオブジェクトを使うと、async/awaitとコールバック形式のコードを併用できます。

通常、アプリケーション水準のコードで Future オブジェクトを作る必要はありません

Future オブジェクトはライブラリや asyncio のAPIで外部に提供されることもあり、await (待機)されることができます:

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

Future オブジェクトを返す低レベル関数の良い例はloop.run_in_executor() です。

Task の作成

ソースコード:Lib/asyncio/tasks.py


asyncio.create_task(coro,*,name=None,context=None)

corocoroutineTask でラップし、その実行をスケジュールします。Task オブジェクトを返します。

Ifname is notNone, it is set as the name of the task usingTask.set_name().

省略可能なキーワード引数context によって、coro を実行するためのカスタムのcontextvars.Context を指定できます。context が省略された場合、現在のコンテキストのコピーが作成されます。

その Task オブジェクトはget_running_loop() から返されたループの中で実行されます。現在のスレッドに実行中のループが無い場合は、RuntimeError が送出されます。

注釈

asyncio.TaskGroup.create_task() is a new alternativeleveraging structural concurrency; it allows for waitingfor a group of related tasks with strong safety guarantees.

重要

タスクが実行中に消えないように、この関数の結果の参照を保存してください。イベントループは弱い参照のみを保持します。ほかに参照元のないタスクは、完了していなくてもガーベジコレクションされる可能性があります。信頼性のある "fire-and-forget" バックグラウンドタスクが必要な場合、コレクションを使ってください。

background_tasks=set()foriinrange(10):task=asyncio.create_task(some_coro(param=i))# Add task to the set. This creates a strong reference.background_tasks.add(task)# To prevent keeping references to finished tasks forever,# make each task remove its own reference from the set after# completion:task.add_done_callback(background_tasks.discard)

Added in version 3.7.

バージョン 3.8 で変更:name パラメータを追加しました。

バージョン 3.11 で変更:context パラメータを追加しました。

タスクのキャンセル

タスクは簡単に、そして安全にキャンセルできます。タスクがキャンセルされた場合、asyncio.CancelledError が次の機会に送出されます。

It is recommended that coroutines usetry/finally blocks to robustlyperform clean-up logic. In caseasyncio.CancelledErroris explicitly caught, it should generally be propagated whenclean-up is complete.asyncio.CancelledError directly subclassesBaseException so most code will not need to be aware of it.

The asyncio components that enable structured concurrency, likeasyncio.TaskGroup andasyncio.timeout(),are implemented using cancellation internally and might misbehave ifa coroutine swallowsasyncio.CancelledError. Similarly, user codeshould not generally calluncancel.However, in cases when suppressingasyncio.CancelledError istruly desired, it is necessary to also calluncancel() to completelyremove the cancellation state.

Task Groups

Task groups combine a task creation API with a convenientand reliable way to wait for all tasks in the group to finish.

classasyncio.TaskGroup

Anasynchronous context managerholding a group of tasks.Tasks can be added to the group usingcreate_task().All tasks are awaited when the context manager exits.

Added in version 3.11.

create_task(coro,*,name=None,context=None)

Create a task in this task group.The signature matches that ofasyncio.create_task().If the task group is inactive (e.g. not yet entered,already finished, or in the process of shutting down),we will close the givencoro.

バージョン 3.13 で変更:Close the given coroutine if the task group is not active.

以下はプログラム例です:

asyncdefmain():asyncwithasyncio.TaskGroup()astg:task1=tg.create_task(some_coro(...))task2=tg.create_task(another_coro(...))print(f"Both tasks have completed now:{task1.result()},{task2.result()}")

Theasyncwith statement will wait for all tasks in the group to finish.While waiting, new tasks may still be added to the group(for example, by passingtg into one of the coroutinesand callingtg.create_task() in that coroutine).Once the last task has finished and theasyncwith block is exited,no new tasks may be added to the group.

The first time any of the tasks belonging to the group failswith an exception other thanasyncio.CancelledError,the remaining tasks in the group are cancelled.No further tasks can then be added to the group.At this point, if the body of theasyncwith statement is still active(i.e.,__aexit__() hasn't been called yet),the task directly containing theasyncwith statement is also cancelled.The resultingasyncio.CancelledError will interrupt anawait,but it will not bubble out of the containingasyncwith statement.

Once all tasks have finished, if any tasks have failedwith an exception other thanasyncio.CancelledError,those exceptions are combined in anExceptionGroup orBaseExceptionGroup(as appropriate; see their documentation)which is then raised.

Two base exceptions are treated specially:If any task fails withKeyboardInterrupt orSystemExit,the task group still cancels the remaining tasks and waits for them,but then the initialKeyboardInterrupt orSystemExitis re-raised instead ofExceptionGroup orBaseExceptionGroup.

If the body of theasyncwith statement exits with an exception(so__aexit__() is called with an exception set),this is treated the same as if one of the tasks failed:the remaining tasks are cancelled and then waited for,and non-cancellation exceptions are grouped into anexception group and raised.The exception passed into__aexit__(),unless it isasyncio.CancelledError,is also included in the exception group.The same special case is made forKeyboardInterrupt andSystemExit as in the previous paragraph.

Task groups are careful not to mix up the internal cancellation used to"wake up" their__aexit__() with cancellation requestsfor the task in which they are running made by other parties.In particular, when one task group is syntactically nested in another,and both experience an exception in one of their child tasks simultaneously,the inner task group will process its exceptions, and then the outer task groupwill receive another cancellation and process its own exceptions.

In the case where a task group is cancelled externally and also mustraise anExceptionGroup, it will call the parent task'scancel() method. This ensures that aasyncio.CancelledError will be raised at the nextawait, so the cancellation is not lost.

Task groups preserve the cancellation countreported byasyncio.Task.cancelling().

バージョン 3.13 で変更:Improved handling of simultaneous internal and external cancellationsand correct preservation of cancellation counts.

Terminating a Task Group

While terminating a task group is not natively supported by the standardlibrary, termination can be achieved by adding an exception-raising taskto the task group and ignoring the raised exception:

importasynciofromasyncioimportTaskGroupclassTerminateTaskGroup(Exception):"""Exception raised to terminate a task group."""asyncdefforce_terminate_task_group():"""Used to force termination of a task group."""raiseTerminateTaskGroup()asyncdefjob(task_id,sleep_time):print(f'Task{task_id}: start')awaitasyncio.sleep(sleep_time)print(f'Task{task_id}: done')asyncdefmain():try:asyncwithTaskGroup()asgroup:# spawn some tasksgroup.create_task(job(1,0.5))group.create_task(job(2,1.5))# sleep for 1 secondawaitasyncio.sleep(1)# add an exception-raising task to force the group to terminategroup.create_task(force_terminate_task_group())except*TerminateTaskGroup:passasyncio.run(main())

予想される出力:

Task 1: startTask 2: startTask 1: done

スリープ

asyncasyncio.sleep(delay,result=None)

delay 秒だけ停止します。

result が提供されている場合は、コルーチン完了時にそれが呼び出し元に返されます。

sleep() は常に現在の Task を一時中断し、他の Task が実行されるのを許可します。

delay を 0 に設定することで、他のタスクを実行可能にする最適な方針を提供します。この方法は、実行時間の長い関数が、その実行時間全体にわたってイベントループをブロックしないようにするために利用できます。

現在の時刻を5秒間、毎秒表示するコルーチンの例:

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())

バージョン 3.10 で変更:loop パラメータが削除されました。

バージョン 3.13 で変更:RaisesValueError ifdelay isnan.

並行な Task 実行

awaitableasyncio.gather(*aws,return_exceptions=False)

aws シーケンスにあるawaitable オブジェクト並行 実行します。

aws にある awaitable がコルーチンである場合、自動的に Task としてスケジュールされます。

全ての awaitable が正常終了した場合、その結果は返り値を集めたリストになります。返り値の順序は、aws での awaitable の順序に相当します。

return_exceptionsFalse である場合(デフォルト)、gather() で await しているタスクに対して、最初の例外が直接伝えられます。aws に並んでいる他の awaitable は、キャンセルされずに 引き続いて実行されます。

return_exceptionsTrue だった場合、例外は成功した結果と同じように取り扱われ、結果リストに集められます。

gather()キャンセル された場合、起動された全ての (未完了の) awaitable もキャンセル されます。

aws シーケンスにある Task あるいは Future がキャンセル された場合、CancelledError を送出したかのうように扱われます。つまり、この場合gather() 呼び出しはキャンセルされません。これは、起動された 1 つの Task あるいは Future のキャンセルが、他の Task あるいは Future のキャンセルを引き起こすのを避けるためです。

注釈

A new alternative to create and run tasks concurrently andwait for their completion isasyncio.TaskGroup.TaskGroupprovides stronger safety guarantees thangather for scheduling a nesting of subtasks:if a task (or a subtask, a task scheduled by a task)raises an exception,TaskGroup will, whilegather will not,cancel the remaining scheduled tasks).

以下はプログラム例です:

importasyncioasyncdeffactorial(name,number):f=1foriinrange(2,number+1):print(f"Task{name}: Compute factorial({number}), currently i={i}...")awaitasyncio.sleep(1)f*=iprint(f"Task{name}: factorial({number}) ={f}")returnfasyncdefmain():# Schedule three calls *concurrently*:L=awaitasyncio.gather(factorial("A",2),factorial("B",3),factorial("C",4),)print(L)asyncio.run(main())# Expected output:##     Task A: Compute factorial(2), currently i=2...#     Task B: Compute factorial(3), currently i=2...#     Task C: Compute factorial(4), currently i=2...#     Task A: factorial(2) = 2#     Task B: Compute factorial(3), currently i=3...#     Task C: Compute factorial(4), currently i=3...#     Task B: factorial(3) = 6#     Task C: Compute factorial(4), currently i=4...#     Task C: factorial(4) = 24#     [2, 6, 24]

注釈

Ifreturn_exceptions is false, cancelling gather() after ithas been marked done won't cancel any submitted awaitables.For instance, gather can be marked done after propagating anexception to the caller, therefore, callinggather.cancel()after catching an exception (raised by one of the awaitables) fromgather won't cancel any other awaitables.

バージョン 3.7 で変更:gather 自身がキャンセルされた場合は、return_exceptions の値に関わらずキャンセルが伝搬されます。

バージョン 3.10 で変更:loop パラメータが削除されました。

バージョン 3.10 で非推奨:Deprecation warning is emitted if no positional arguments are providedor not all positional arguments are Future-like objectsand there is no running event loop.

Eager Task Factory

asyncio.eager_task_factory(loop,coro,*,name=None,context=None)

A task factory for eager task execution.

When using this factory (vialoop.set_task_factory(asyncio.eager_task_factory)),coroutines begin execution synchronously duringTask construction.Tasks are only scheduled on the event loop if they block.This can be a performance improvement as the overhead of loop schedulingis avoided for coroutines that complete synchronously.

A common example where this is beneficial is coroutines which employcaching or memoization to avoid actual I/O when possible.

注釈

Immediate execution of the coroutine is a semantic change.If the coroutine returns or raises, the task is never scheduledto the event loop. If the coroutine execution blocks, the task isscheduled to the event loop. This change may introduce behaviorchanges to existing applications. For example,the application's task execution order is likely to change.

Added in version 3.12.

asyncio.create_eager_task_factory(custom_task_constructor)

Create an eager task factory, similar toeager_task_factory(),using the providedcustom_task_constructor when creating a new task insteadof the defaultTask.

custom_task_constructor must be acallable with the signature matchingthe signature ofTask.__init__.The callable must return aasyncio.Task-compatible object.

This function returns acallable intended to be used as a task factory of anevent loop vialoop.set_task_factory(factory)).

Added in version 3.12.

キャンセルからの保護

awaitableasyncio.shield(aw)

キャンセル からawaitable オブジェクト を保護します。

aw がコルーチンだった場合、自動的に Task としてスケジュールされます。

文:

task=asyncio.create_task(something())res=awaitshield(task)

は、以下と同じです

res=awaitsomething()

それを含むコルーチンがキャンセルされた場合を除きsomething() 内で動作している Task はキャンセルされません。something() 側から見るとキャンセルは発生しません。呼び出し元がキャンセルされた場合でも、 "await" 式はCancelledError を送出します。

注意:something() が他の理由 (例えば、原因が自分自身) でキャンセルされた場合はshield() でも保護できません。

完全にキャンセルを無視したい場合 (推奨はしません) は、shield() 関数は次のように try/except 節と組み合わせることになるでしょう:

task=asyncio.create_task(something())try:res=awaitshield(task)exceptCancelledError:res=None

重要

Save a reference to tasks passed to this function, to avoida task disappearing mid-execution. The event loop only keepsweak references to tasks. A task that isn't referenced elsewheremay get garbage collected at any time, even before it's done.

バージョン 3.10 で変更:loop パラメータが削除されました。

バージョン 3.10 で非推奨:Deprecation warning is emitted ifaw is not Future-like objectand there is no running event loop.

タイムアウト

asyncio.timeout(delay)

Return anasynchronous context managerthat can be used to limit the amount of time spent waiting onsomething.

delay can either beNone, or a float/int number ofseconds to wait. Ifdelay isNone, no time limit willbe applied; this can be useful if the delay is unknown whenthe context manager is created.

In either case, the context manager can be rescheduled aftercreation usingTimeout.reschedule().

以下はプログラム例です:

asyncdefmain():asyncwithasyncio.timeout(10):awaitlong_running_task()

Iflong_running_task takes more than 10 seconds to complete,the context manager will cancel the current task and handlethe resultingasyncio.CancelledError internally, transforming itinto aTimeoutError which can be caught and handled.

注釈

Theasyncio.timeout() context manager is what transformstheasyncio.CancelledError into aTimeoutError,which means theTimeoutError can only be caughtoutside of the context manager.

Example of catchingTimeoutError:

asyncdefmain():try:asyncwithasyncio.timeout(10):awaitlong_running_task()exceptTimeoutError:print("The long operation timed out, but we've handled it.")print("This statement will run regardless.")

The context manager produced byasyncio.timeout() can berescheduled to a different deadline and inspected.

classasyncio.Timeout(when)

Anasynchronous context managerfor cancelling overdue coroutines.

when should be an absolute time at which the context should time out,as measured by the event loop's clock:

  • Ifwhen isNone, the timeout will never trigger.

  • Ifwhen<loop.time(), the timeout will trigger on the nextiteration of the event loop.

when()float|None

Return the current deadline, orNone if the currentdeadline is not set.

reschedule(when:float|None)

Reschedule the timeout.

expired()bool

Return whether the context manager has exceeded its deadline(expired).

以下はプログラム例です:

asyncdefmain():try:# We do not know the timeout when starting, so we pass ``None``.asyncwithasyncio.timeout(None)ascm:# We know the timeout now, so we reschedule it.new_deadline=get_running_loop().time()+10cm.reschedule(new_deadline)awaitlong_running_task()exceptTimeoutError:passifcm.expired():print("Looks like we haven't finished on time.")

Timeout context managers can be safely nested.

Added in version 3.11.

asyncio.timeout_at(when)

Similar toasyncio.timeout(), exceptwhen is the absolute timeto stop waiting, orNone.

以下はプログラム例です:

asyncdefmain():loop=get_running_loop()deadline=loop.time()+20try:asyncwithasyncio.timeout_at(deadline):awaitlong_running_task()exceptTimeoutError:print("The long operation timed out, but we've handled it.")print("This statement will run regardless.")

Added in version 3.11.

asyncasyncio.wait_for(aw,timeout)

awawaitable が、完了するかタイムアウトになるのを待ちます。

aw がコルーチンだった場合、自動的に Task としてスケジュールされます。

timeout にはNone もしくは待つ秒数の浮動小数点数か整数を指定できます。timeoutNone の場合、 Future が完了するまで待ちます。

If a timeout occurs, it cancels the task and raisesTimeoutError.

Task のキャンセル を避けるためには、shield() の中にラップしてください。

この関数は future が実際にキャンセルされるまで待つため、待ち時間の合計はtimeout を超えることがあります。キャンセル中に例外が発生した場合は、その例外は伝達されます。

待機が中止された場合aw も中止されます。

以下はプログラム例です:

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

バージョン 3.7 で変更:Whenaw is cancelled due to a timeout,wait_for waitsforaw to be cancelled. Previously, it raisedTimeoutError immediately.

バージョン 3.10 で変更:loop パラメータが削除されました。

バージョン 3.11 で変更:RaisesTimeoutError instead ofasyncio.TimeoutError.

要素の終了待機

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

RunFuture andTask instances in theawsiterable concurrently and block until the condition specifiedbyreturn_when.

イテラブルaws は空であってはなりません。

Task/Future からなる 2 つの集合(done,pending) を返します。

使い方:

done,pending=awaitasyncio.wait(aws)

timeout (浮動小数点数または整数) が指定されていたら、処理を返すのを待つ最大秒数を制御するのに使われます。

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

return_when でこの関数がいつ結果を返すか指定します。指定できる値は以下の 定数のどれか一つです:

定数

説明

asyncio.FIRST_COMPLETED

いずれかのフューチャが終了したかキャンセルされたときに返します。

asyncio.FIRST_EXCEPTION

The function will return when any future finishes by raising anexception. If no future raises an exceptionthen it is equivalent toALL_COMPLETED.

asyncio.ALL_COMPLETED

すべてのフューチャが終了したかキャンセルされたときに返します。

wait_for() と異なり、wait() はタイムアウトが起きたときに Future をキャンセルしません。

バージョン 3.10 で変更:loop パラメータが削除されました。

バージョン 3.11 で変更:Passing coroutine objects towait() directly is forbidden.

バージョン 3.12 で変更:Added support for generators yielding tasks.

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

Runawaitable objects in theaws iterableconcurrently. The returned object can be iterated to obtain the resultsof the awaitables as they finish.

The object returned byas_completed() can be iterated as anasynchronous iterator or a plainiterator. When asynchronousiteration is used, the originally-supplied awaitables are yielded if theyare tasks or futures. This makes it easy to correlate previously-scheduledtasks with their results. Example:

ipv4_connect=create_task(open_connection("127.0.0.1",80))ipv6_connect=create_task(open_connection("::1",80))tasks=[ipv4_connect,ipv6_connect]asyncforearliest_connectinas_completed(tasks):# earliest_connect is done. The result can be obtained by# awaiting it or calling earliest_connect.result()reader,writer=awaitearliest_connectifearliest_connectisipv6_connect:print("IPv6 connection established.")else:print("IPv4 connection established.")

During asynchronous iteration, implicitly-created tasks will be yielded forsupplied awaitables that aren't tasks or futures.

When used as a plain iterator, each iteration yields a new coroutine thatreturns the result or raises the exception of the next completed awaitable.This pattern is compatible with Python versions older than 3.13:

ipv4_connect=create_task(open_connection("127.0.0.1",80))ipv6_connect=create_task(open_connection("::1",80))tasks=[ipv4_connect,ipv6_connect]fornext_connectinas_completed(tasks):# next_connect is not one of the original task objects. It must be# awaited to obtain the result value or raise the exception of the# awaitable that finishes next.reader,writer=awaitnext_connect

ATimeoutError is raised if the timeout occurs before all awaitablesare done. This is raised by theasyncfor loop during asynchronousiteration or by the coroutines yielded during plain iteration.

バージョン 3.10 で変更:loop パラメータが削除されました。

バージョン 3.10 で非推奨:Deprecation warning is emitted if not all awaitable objects in theawsiterable are Future-like objects and there is no running event loop.

バージョン 3.12 で変更:Added support for generators yielding tasks.

バージョン 3.13 で変更:The result can now be used as either anasynchronous iteratoror as a plainiterator (previously it was only a plain iterator).

スレッド内での実行

asyncasyncio.to_thread(func,/,*args,**kwargs)

別のスレッドで非同期的に関数func を実行します。

この関数に渡された *args と **kwargs は関数func に直接渡されます。また、イベントループスレッドのコンテキスト変数に関数を実行するスレッドからアクセスできるように、現在のcontextvars.Context も伝播されます。

関数func の最終結果を待ち受けできるコルーチンを返します。

This coroutine function is primarily intended to be used for executingIO-bound functions/methods that would otherwise block the event loop ifthey were run in the main thread. For example:

defblocking_io():print(f"start blocking_io at{time.strftime('%X')}")# Note that time.sleep() can be replaced with any blocking# IO-bound operation, such as file operations.time.sleep(1)print(f"blocking_io complete at{time.strftime('%X')}")asyncdefmain():print(f"started main at{time.strftime('%X')}")awaitasyncio.gather(asyncio.to_thread(blocking_io),asyncio.sleep(1))print(f"finished main at{time.strftime('%X')}")asyncio.run(main())# Expected output:## started main at 19:50:53# start blocking_io at 19:50:53# blocking_io complete at 19:50:54# finished main at 19:50:54

Directly callingblocking_io() in any coroutine would block the event loopfor its duration, resulting in an additional 1 second of run time. Instead,by usingasyncio.to_thread(), we can run it in a separate thread withoutblocking the event loop.

注釈

Due to theGIL,asyncio.to_thread() can typically only be usedto make IO-bound functions non-blocking. However, for extension modulesthat release the GIL or alternative Python implementations that don'thave one,asyncio.to_thread() can also be used for CPU-bound functions.

Added in version 3.9.

外部スレッドからのスケジュール

asyncio.run_coroutine_threadsafe(coro,loop)

与えられたイベントループにコルーチンを送ります。この処理は、スレッドセーフです。

他の OS スレッドから結果を待つためのconcurrent.futures.Future を返します。

この関数は、イベントループが動作しているスレッドとは異なる OS スレッドから呼び出すためのものです。例えば次のように使います:

# 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

コルーチンから例外が送出された場合、返された Future に通知されます。これはイベントループの Task をキャンセルするのにも使えます:

try:result=future.result(timeout)exceptTimeoutError: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}')

このドキュメントの並行処理とマルチスレッド処理 節を参照してください。

他の asyncio 関数とは異なり、この関数は明示的に渡されるloop 引数を必要とします。

Added in version 3.5.1.

イントロスペクション

asyncio.current_task(loop=None)

現在実行中のTask インスタンスを返します。実行中の Task が無い場合はNone を返します。

loopNone の場合、get_running_loop() が現在のループを取得するのに使われます。

Added in version 3.7.

asyncio.all_tasks(loop=None)

ループで実行されたTask オブジェクトでまだ完了していないものの集合を返します。

loopNone の場合、get_running_loop() は現在のループを取得するのに使われます。

Added in version 3.7.

asyncio.iscoroutine(obj)

ReturnTrue ifobj is a coroutine object.

Added in version 3.4.

Task オブジェクト

classasyncio.Task(coro,*,loop=None,name=None,context=None,eager_start=False)

Pythonコルーチン を実行するFuture オブジェクトです。スレッドセーフではありません。

Task はイベントループのコルーチンを実行するのに使われます。Future でコルーチンが待機している場合、 Task は自身のコルーチンの実行を一時停止させ、 Future の完了を待ちます。Future が完了 したら、 Task が内包しているコルーチンの実行を再開します。

イベントループは協調スケジューリングを使用します。つまり、イベントループは同時に 1 つの Task のみ実行します。Task が Future の完了を待っているときは、イベントループは他の Task やコールバックを動作させるか、 IO 処理を実行します。

Task を作成するには高レベルのasyncio.create_task() 関数、あるいは低レベルのloop.create_task() 関数やensure_future() 関数を使用してください。手作業での Task の実装は推奨されません。

実行中のタスクをキャンセルするためには、cancel() メソッドを使用します。このメソッドを呼ぶと、タスクはそれを内包するコルーチンに対してCancelledError 例外を送出します。キャンセルの際にコルーチンが Future オブジェクトを待っていた場合、その Future オブジェクトはキャンセルされます。

cancelled() は、タスクがキャンセルされたかを調べるのに使用できます。タスクを内包するコルーチンでCancelledError 例外が抑制されておらず、かつタスクが実際にキャンセルされている場合に、このメソッドはTrue を変えます。

asyncio.Task は、Future.set_result()Future.set_exception() を除いて、Future の API をすべて継承しています。

An optional keyword-onlycontext argument allows specifying acustomcontextvars.Context for thecoro to run in.If nocontext is provided, the Task copies the current contextand later runs its coroutine in the copied context.

An optional keyword-onlyeager_start argument allows eagerly startingthe execution of theasyncio.Task at task creation time.If set toTrue and the event loop is running, the task will startexecuting the coroutine immediately, until the first time the coroutineblocks. If the coroutine returns or raises without blocking, the taskwill be finished eagerly and will skip scheduling to the event loop.

バージョン 3.7 で変更:contextvars モジュールのサポートを追加。

バージョン 3.8 で変更:name パラメータを追加しました。

バージョン 3.10 で非推奨:Deprecation warning is emitted ifloop is not specifiedand there is no running event loop.

バージョン 3.11 で変更:context パラメータを追加しました。

バージョン 3.12 で変更:Added theeager_start parameter.

done()

Task が完了 しているならTrue を返します。

Task がラップしているコルーチンが値を返すか、例外を送出するか、または Task がキャンセルされたとき、 Task は完了 します。

result()

Task の結果を返します。

Task が完了 している場合、ラップしているコルーチンの結果が返されます (コルーチンが例外を送出された場合、その例外が例外が再送出されます)

Task がキャンセル されている場合、このメソッドはCancelledError 例外を送出します。

If the Task's result isn't yet available, this method raisesanInvalidStateError exception.

exception()

Task の例外を返します。

ラップされたコルーチンが例外を送出した場合、その例外が返されます。ラップされたコルーチンが正常終了した場合、このメソッドはNone を返します。

Task がキャンセル されている場合、このメソッドはCancelledError 例外を送出します。

Task がまだ完了 していない場合、このメソッドはInvalidStateError 例外を送出します。

add_done_callback(callback,*,context=None)

Task が完了 したときに実行されるコールバックを追加します。

このメソッドは低水準のコールバックベースのコードでのみ使うべきです。

詳細についてはFuture.add_done_callback() のドキュメントを参照してください。

remove_done_callback(callback)

コールバックリストからcallback を削除します。

このメソッドは低水準のコールバックベースのコードでのみ使うべきです。

詳細についてはFuture.remove_done_callback() のドキュメントを参照してください。

get_stack(*,limit=None)

このタスクのスタックフレームのリストを返します。

コルーチンが完了していない場合、これはサスペンドされた時点でのスタックを返します。コルーチンが正常に処理を完了したか、キャンセルされていた場合は空のリストを返します。コルーチンが例外で終了した場合はトレースバックフレームのリストを返します。

フレームは常に古いものから新しい物へ並んでいます。

サスペンドされているコルーチンの場合スタックフレームが 1 個だけ返されます。

オプション引数limit は返すフレームの最大数を指定します; デフォルトでは取得可能な全てのフレームを返します。返されるリストの順番は、スタックが返されるか、トレースバックが返されるかによって変わります: スタックでは新しい順に並んだリストが返されますが、トレースバックでは古い順に並んだリストが返されます(これは traceback モジュールの振る舞いと一致します)。

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

このタスクのスタックまたはトレースバックを出力します。

このメソッドはget_stack() によって取得されるフレームに対し、 traceback モジュールと同じような出力を生成します。

引数limitget_stack() にそのまま渡されます。

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

get_coro()

Task がラップしているコルーチンオブジェクトを返します。

注釈

This will returnNone for Tasks which have alreadycompleted eagerly. See theEager Task Factory.

Added in version 3.8.

バージョン 3.12 で変更:Newly added eager task execution means result may beNone.

get_context()

Return thecontextvars.Context objectassociated with the task.

Added in version 3.12.

get_name()

Task の名前を返します。

Task に対して明示的に名前が設定されていない場合, デフォルトの asyncio Task 実装はタスクをインスタンス化する際にデフォルトの名前を生成します。

Added in version 3.8.

set_name(value)

Task に名前を設定します。

引数value は文字列に変換可能なオブジェクトであれば何でもかまいません。

Task のデフォルト実装では、名前はオブジェクトのrepr() メソッドの出力で確認できます。

Added in version 3.8.

cancel(msg=None)

このタスクに、自身のキャンセルを要求します。

If the Task is alreadydone orcancelled, returnFalse,otherwise, returnTrue.

The method 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 ......exceptCancelledError ...finally block.Therefore, unlikeFuture.cancel(),Task.cancel() doesnot guarantee that the Task will be cancelled, althoughsuppressing cancellation completely is not common and is activelydiscouraged. Should the coroutine nevertheless decide to suppressthe cancellation, it needs to callTask.uncancel() in additionto catching the exception.

バージョン 3.9 で変更:Added themsg parameter.

バージョン 3.11 で変更:Themsg parameter is propagated from cancelled task to its awaiter.

以下の例は、コルーチンがどのようにしてキャンセルのリクエストを阻止するかを示しています:

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()

Task がキャンセルされた 場合にTrue を返します。

cancel() メソッドによりキャンセルがリクエストされ、かつ Task がラップしているコルーチンが内部で送出されたCancelledError 例外を伝達したとき、 Task は実際にキャンセル されます。

uncancel()

Decrement the count of cancellation requests to this Task.

Returns the remaining number of cancellation requests.

Note that once execution of a cancelled task completed, furthercalls touncancel() are ineffective.

Added in version 3.11.

This method is used by asyncio's internals and isn't expected to beused by end-user code. In particular, if a Task gets successfullyuncancelled, this allows for elements of structured concurrency likeTask Groups andasyncio.timeout() to continue running,isolating cancellation to the respective structured block.For example:

asyncdefmake_request_with_timeout():try:asyncwithasyncio.timeout(1):# Structured block affected by the timeout:awaitmake_request()awaitmake_another_request()exceptTimeoutError:log("There was a timeout")# Outer code not affected by the timeout:awaitunrelated_code()

While the block withmake_request() andmake_another_request()might get cancelled due to the timeout,unrelated_code() shouldcontinue running even in case of the timeout. This is implementedwithuncancel().TaskGroup context managers useuncancel() in a similar fashion.

If end-user code is, for some reason, suppressing cancellation bycatchingCancelledError, it needs to call this method to removethe cancellation state.

When this method decrements the cancellation count to zero,the method checks if a previouscancel() call had arrangedforCancelledError to be thrown into the task.If it hasn't been thrown yet, that arrangement will berescinded (by resetting the internal_must_cancel flag).

バージョン 3.13 で変更:Changed to rescind pending cancellation requests upon reaching zero.

cancelling()

Return the number of pending cancellation requests to this Task, i.e.,the number of calls tocancel() less the number ofuncancel() calls.

Note that if this number is greater than zero but the Task isstill executing,cancelled() will still returnFalse.This is because this number can be lowered by callinguncancel(),which can lead to the task not being cancelled after all if thecancellation requests go down to zero.

This method is used by asyncio's internals and isn't expected to beused by end-user code. Seeuncancel() for more details.

Added in version 3.11.