コルーチンと Task
*****************

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

* コルーチン

* Awaitable

* Task の作成

* タスクのキャンセル

* Task Groups

* スリープ

* 並行な Task 実行

* Eager Task Factory

* キャンセルからの保護

* タイムアウト

* 要素の終了待機

* スレッド内での実行

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

* イントロスペクション

* Task オブジェクト


コルーチン
==========

**Source code:** Lib/asyncio/coroutines.py

======================================================================

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

   >>> import asyncio

   >>> async def main():
   ...     print('hello')
   ...     await asyncio.sleep(1)
   ...     print('world')

   >>> asyncio.run(main())
   hello
   world

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

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

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

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

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

     import asyncio
     import time

     async def say_after(delay, what):
         await asyncio.sleep(delay)
         print(what)

     async def main():
         print(f"started at {time.strftime('%X')}")

         await say_after(1, 'hello')
         await say_after(2, 'world')

         print(f"finished at {time.strftime('%X')}")

     asyncio.run(main())

  予想される出力:

     started at 17:13:52
     hello
     world
     finished at 17:13:55

* asyncio の "Tasks" としてコルーチンを並行して走らせる
  "asyncio.create_task()" 関数。

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

     async def main():
         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.)
         await task1
         await task2

         print(f"finished at {time.strftime('%X')}")

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

     started at 17:14:32
     hello
     world
     finished at 17:14:34

* The "asyncio.TaskGroup" class provides a more modern alternative to
  "create_task()". Using this API, the last example becomes:

     async def main():
         async with asyncio.TaskGroup() as tg:
             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* であり、他のコルーチンから待機される
ことができます:

   import asyncio

   async def nested():
       return 42

   async def main():
       # 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(await nested())  # will print "42".

   asyncio.run(main())

重要:

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

  * *コルーチン関数*: "async def" 関数;

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

-[ Task ]-

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

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

   import asyncio

   async def nested():
       return 42

   async def main():
       # 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:
       await task

   asyncio.run(main())

-[ Future ]-

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

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

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

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

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

   async def main():
       await function_that_returns_a_future_object()

       # this is also valid:
       await asyncio.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, eager_start=None, **kwargs)

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

   The full function signature is largely the same as that of the
   "Task" constructor (or factory) - all of the keyword arguments to
   this function are passed through to that interface.

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

   An optional keyword-only *eager_start* argument allows specifying
   if the task should execute eagerly during the call to create_task,
   or be scheduled later. If *eager_start* is not passed the mode set
   by "loop.set_task_factory()" will be used.

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

   注釈:

     "asyncio.TaskGroup.create_task()" is a new alternative leveraging
     structural concurrency; it allows for waiting for a group of
     related tasks with strong safety guarantees.

   重要:

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

        background_tasks = set()

        for i in range(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* パラメータを追加しました。

   バージョン 3.14 で変更: Added the *eager_start* parameter by
   passing on all *kwargs*.


タスクのキャンセル
==================

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

It is recommended that coroutines use "try/finally" blocks to robustly
perform clean-up logic. In case "asyncio.CancelledError" is explicitly
caught, it should generally be propagated when clean-up is complete.
"asyncio.CancelledError" directly subclasses "BaseException" so most
code will not need to be aware of it.

The asyncio components that enable structured concurrency, like
"asyncio.TaskGroup" and "asyncio.timeout()", are implemented using
cancellation internally and might misbehave if a coroutine swallows
"asyncio.CancelledError". Similarly, user code should not generally
call "uncancel". However, in cases when suppressing
"asyncio.CancelledError" is truly desired, it is necessary to also
call "uncancel()" to completely remove the cancellation state.


Task Groups
===========

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

class asyncio.TaskGroup

   An asynchronous context manager holding a group of tasks. Tasks can
   be added to the group using "create_task()". All tasks are awaited
   when the context manager exits.

   Added in version 3.11.

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

      Create a task in this task group. The signature matches that of
      "asyncio.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 given "coro".

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

      バージョン 3.14 で変更: Passes on all *kwargs* to
      "loop.create_task()"

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

   async def main():
       async with asyncio.TaskGroup() as tg:
           task1 = tg.create_task(some_coro(...))
           task2 = tg.create_task(another_coro(...))
       print(f"Both tasks have completed now: {task1.result()}, {task2.result()}")

The "async with" 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 passing "tg" into one of the coroutines and calling
"tg.create_task()" in that coroutine). Once the last task has finished
and the "async with" block is exited, no new tasks may be added to the
group.

The first time any of the tasks belonging to the group fails with an
exception other than "asyncio.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 the "async with" statement is
still active (i.e., "__aexit__()" hasn't been called yet), the task
directly containing the "async with" statement is also cancelled. The
resulting "asyncio.CancelledError" will interrupt an "await", but it
will not bubble out of the containing "async with" statement.

Once all tasks have finished, if any tasks have failed with an
exception other than "asyncio.CancelledError", those exceptions are
combined in an "ExceptionGroup" or "BaseExceptionGroup" (as
appropriate; see their documentation) which is then raised.

Two base exceptions are treated specially: If any task fails with
"KeyboardInterrupt" or "SystemExit", the task group still cancels the
remaining tasks and waits for them, but then the initial
"KeyboardInterrupt" or "SystemExit" is re-raised instead of
"ExceptionGroup" or "BaseExceptionGroup".

If the body of the "async with" 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
an exception group and raised. The exception passed into
"__aexit__()", unless it is "asyncio.CancelledError", is also included
in the exception group. The same special case is made for
"KeyboardInterrupt" and "SystemExit" as in the previous paragraph.

Task groups are careful not to mix up the internal cancellation used
to "wake up" their "__aexit__()" with cancellation requests for 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 group will receive another cancellation and process its own
exceptions.

In the case where a task group is cancelled externally and also must
raise an "ExceptionGroup", it will call the parent task's "cancel()"
method. This ensures that a "asyncio.CancelledError" will be raised at
the next "await", so the cancellation is not lost.

Task groups preserve the cancellation count reported by
"asyncio.Task.cancelling()".

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


Terminating a Task Group
------------------------

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

   import asyncio
   from asyncio import TaskGroup

   class TerminateTaskGroup(Exception):
       """Exception raised to terminate a task group."""

   async def force_terminate_task_group():
       """Used to force termination of a task group."""
       raise TerminateTaskGroup()

   async def job(task_id, sleep_time):
       print(f'Task {task_id}: start')
       await asyncio.sleep(sleep_time)
       print(f'Task {task_id}: done')

   async def main():
       try:
           async with TaskGroup() as group:
               # spawn some tasks
               group.create_task(job(1, 0.5))
               group.create_task(job(2, 1.5))
               # sleep for 1 second
               await asyncio.sleep(1)
               # add an exception-raising task to force the group to terminate
               group.create_task(force_terminate_task_group())
       except* TerminateTaskGroup:
           pass

   asyncio.run(main())

予想される出力:

   Task 1: start
   Task 2: start
   Task 1: done


スリープ
========

async asyncio.sleep(delay, result=None)

   *delay* 秒だけ停止します。

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

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

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

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

      import asyncio
      import datetime

      async def display_date():
          loop = asyncio.get_running_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)

      asyncio.run(display_date())

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

   バージョン 3.13 で変更: Raises "ValueError" if *delay* is "nan".


並行な Task 実行
================

awaitable asyncio.gather(*aws, return_exceptions=False)

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

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

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

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

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

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

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

   注釈:

     A new alternative to create and run tasks concurrently and wait
     for their completion is "asyncio.TaskGroup". *TaskGroup* provides
     stronger safety guarantees than *gather* for scheduling a nesting
     of subtasks: if a task (or a subtask, a task scheduled by a task)
     raises an exception, *TaskGroup* will, while *gather* will not,
     cancel the remaining scheduled tasks).

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

      import asyncio

      async def factorial(name, number):
          f = 1
          for i in range(2, number + 1):
              print(f"Task {name}: Compute factorial({number}), currently i={i}...")
              await asyncio.sleep(1)
              f *= i
          print(f"Task {name}: factorial({number}) = {f}")
          return f

      async def main():
          # Schedule three calls *concurrently*:
          L = await asyncio.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]

   注釈:

     If *return_exceptions* is false, cancelling gather() after it has
     been marked done won't cancel any submitted awaitables. For
     instance, gather can be marked done after propagating an
     exception to the caller, therefore, calling "gather.cancel()"
     after catching an exception (raised by one of the awaitables)
     from gather 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 provided or not all positional arguments
   are Future-like objects and 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 (via
   "loop.set_task_factory(asyncio.eager_task_factory)"), coroutines
   begin execution synchronously during "Task" construction. Tasks are
   only scheduled on the event loop if they block. This can be a
   performance improvement as the overhead of loop scheduling is
   avoided for coroutines that complete synchronously.

   A common example where this is beneficial is coroutines which
   employ caching 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 scheduled to the
     event loop. If the coroutine execution blocks, the task is
     scheduled to the event loop. This change may introduce behavior
     changes 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 to "eager_task_factory()",
   using the provided *custom_task_constructor* when creating a new
   task instead of the default "Task".

   *custom_task_constructor* must be a *callable* with the signature
   matching the signature of "Task.__init__". The callable must return
   a "asyncio.Task"-compatible object.

   This function returns a *callable* intended to be used as a task
   factory of an event loop via "loop.set_task_factory(factory)").

   Added in version 3.12.


キャンセルからの保護
====================

awaitable asyncio.shield(aw)

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

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

   文:

      task = asyncio.create_task(something())
      res = await shield(task)

   は、以下と同じです

      res = await something()

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

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

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

      task = asyncio.create_task(something())
      try:
          res = await shield(task)
      except CancelledError:
          res = None

   重要:

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

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

   バージョン 3.10 で非推奨: Deprecation warning is emitted if *aw* is
   not Future-like object and there is no running event loop.


タイムアウト
============

asyncio.timeout(delay)

   Return an asynchronous context manager that can be used to limit
   the amount of time spent waiting on something.

   *delay* can either be "None", or a float/int number of seconds to
   wait. If *delay* is "None", no time limit will be applied; this can
   be useful if the delay is unknown when the context manager is
   created.

   In either case, the context manager can be rescheduled after
   creation using "Timeout.reschedule()".

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

      async def main():
          async with asyncio.timeout(10):
              await long_running_task()

   If "long_running_task" takes more than 10 seconds to complete, the
   context manager will cancel the current task and handle the
   resulting "asyncio.CancelledError" internally, transforming it into
   a "TimeoutError" which can be caught and handled.

   注釈:

     The "asyncio.timeout()" context manager is what transforms the
     "asyncio.CancelledError" into a "TimeoutError", which means the
     "TimeoutError" can only be caught *outside* of the context
     manager.

   Example of catching "TimeoutError":

      async def main():
          try:
              async with asyncio.timeout(10):
                  await long_running_task()
          except TimeoutError:
              print("The long operation timed out, but we've handled it.")

          print("This statement will run regardless.")

   The context manager produced by "asyncio.timeout()" can be
   rescheduled to a different deadline and inspected.

   class asyncio.Timeout(when)

      An asynchronous context manager for cancelling overdue
      coroutines.

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

      * If "when" is "None", the timeout will never trigger.

      * If "when < loop.time()", the timeout will trigger on the next
        iteration of the event loop.

         when() -> float | None

            Return the current deadline, or "None" if the current
            deadline is not set.

         reschedule(when: float | None)

            Reschedule the timeout.

         expired() -> bool

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

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

      async def main():
          try:
              # We do not know the timeout when starting, so we pass ``None``.
              async with asyncio.timeout(None) as cm:
                  # We know the timeout now, so we reschedule it.
                  new_deadline = get_running_loop().time() + 10
                  cm.reschedule(new_deadline)

                  await long_running_task()
          except TimeoutError:
              pass

          if cm.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 to "asyncio.timeout()", except *when* is the absolute time
   to stop waiting, or "None".

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

      async def main():
          loop = get_running_loop()
          deadline = loop.time() + 20
          try:
              async with asyncio.timeout_at(deadline):
                  await long_running_task()
          except TimeoutError:
              print("The long operation timed out, but we've handled it.")

          print("This statement will run regardless.")

   Added in version 3.11.

async asyncio.wait_for(aw, timeout)

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

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

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

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

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

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

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

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

      async def eternity():
          # Sleep for one hour
          await asyncio.sleep(3600)
          print('yay!')

      async def main():
          # Wait for at most 1 second
          try:
              await asyncio.wait_for(eternity(), timeout=1.0)
          except TimeoutError:
              print('timeout!')

      asyncio.run(main())

      # Expected output:
      #
      #     timeout!

   バージョン 3.7 で変更: When *aw* is cancelled due to a timeout,
   "wait_for" waits for *aw* to be cancelled.  Previously, it raised
   "TimeoutError" immediately.

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

   バージョン 3.11 で変更: Raises "TimeoutError" instead of
   "asyncio.TimeoutError".


要素の終了待機
==============

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

   Run "Future" and "Task" instances in the *aws* iterable
   concurrently and block until the condition specified by
   *return_when*.

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

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

   使い方:

      done, pending = await asyncio.wait(aws)

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

   Note that this function does not raise "TimeoutError". Futures or
   Tasks that aren't done when the timeout occurs are simply returned
   in the second set.

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

   +----------------------------------------------------+----------------------------------------------------+
   | 定数                                               | 説明                                               |
   |====================================================|====================================================|
   | asyncio.FIRST_COMPLETED                            | いずれかのフューチャが終了したかキャンセルされたと |
   |                                                    | きに返します。                                     |
   +----------------------------------------------------+----------------------------------------------------+
   | asyncio.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".                                   |
   +----------------------------------------------------+----------------------------------------------------+
   | asyncio.ALL_COMPLETED                              | すべてのフューチャが終了したかキャンセルされたとき |
   |                                                    | に返します。                                       |
   +----------------------------------------------------+----------------------------------------------------+

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

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

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

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

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

   Run awaitable objects in the *aws* iterable concurrently. The
   returned object can be iterated to obtain the results of the
   awaitables as they finish.

   The object returned by "as_completed()" can be iterated as an
   *asynchronous iterator* or a plain *iterator*. When asynchronous
   iteration is used, the originally-supplied awaitables are yielded
   if they are tasks or futures. This makes it easy to correlate
   previously-scheduled tasks 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]

      async for earliest_connect in as_completed(tasks):
          # earliest_connect is done. The result can be obtained by
          # awaiting it or calling earliest_connect.result()
          reader, writer = await earliest_connect

          if earliest_connect is ipv6_connect:
              print("IPv6 connection established.")
          else:
              print("IPv4 connection established.")

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

   When used as a plain iterator, each iteration yields a new
   coroutine that returns 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]

      for next_connect in as_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 = await next_connect

   A "TimeoutError" is raised if the timeout occurs before all
   awaitables are done. This is raised by the "async for" loop during
   asynchronous iteration or by the coroutines yielded during plain
   iteration.

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

   バージョン 3.10 で非推奨: Deprecation warning is emitted if not all
   awaitable objects in the *aws* iterable 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 an
   *asynchronous iterator* or as a plain *iterator* (previously it was
   only a plain iterator).


スレッド内での実行
==================

async asyncio.to_thread(func, /, *args, **kwargs)

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

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

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

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

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

      async def main():
          print(f"started main at {time.strftime('%X')}")

          await asyncio.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 calling "blocking_io()" in any coroutine would block the
   event loop for its duration, resulting in an additional 1 second of
   run time. Instead, by using "asyncio.to_thread()", we can run it in
   a separate thread without blocking the event loop.

   注釈:

     Due to the *GIL*, "asyncio.to_thread()" can typically only be
     used to make IO-bound functions non-blocking. However, for
     extension modules that release the GIL or alternative Python
     implementations that don't have 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 スレ
   ッドから呼び出すためのものです。 例えば次のように使います:

      def in_thread(loop: asyncio.AbstractEventLoop) -> None:
          # Run some blocking IO
          pathlib.Path("example.txt").write_text("hello world", encoding="utf8")

          # Create a coroutine
          coro = asyncio.sleep(1, result=3)

          # Submit the coroutine to a given loop
          future = asyncio.run_coroutine_threadsafe(coro, loop)

          # Wait for the result with an optional timeout argument
          assert future.result(timeout=2) == 3

      async def amain() -> None:
          # Get the running loop
          loop = asyncio.get_running_loop()

          # Run something in a thread
          await asyncio.to_thread(in_thread, loop)

   It's also possible to run the other way around.  Example:

      @contextlib.contextmanager
      def loop_in_thread() -> Generator[asyncio.AbstractEventLoop]:
          loop_fut = concurrent.futures.Future[asyncio.AbstractEventLoop]()
          stop_event = asyncio.Event()

          async def main() -> None:
              loop_fut.set_result(asyncio.get_running_loop())
              await stop_event.wait()

          with concurrent.futures.ThreadPoolExecutor(1) as tpe:
              complete_fut = tpe.submit(asyncio.run, main())
              for fut in concurrent.futures.as_completed((loop_fut, complete_fut)):
                  if fut is loop_fut:
                      loop = loop_fut.result()
                      try:
                          yield loop
                      finally:
                          loop.call_soon_threadsafe(stop_event.set)
                  else:
                      fut.result()

      # Create a loop in another thread
      with loop_in_thread() as loop:
          # Create a coroutine
          coro = asyncio.sleep(1, result=3)

          # Submit the coroutine to a given loop
          future = asyncio.run_coroutine_threadsafe(coro, loop)

          # Wait for the result with an optional timeout argument
          assert future.result(timeout=2) == 3

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

      try:
          result = future.result(timeout)
      except TimeoutError:
          print('The coroutine took too long, cancelling the task...')
          future.cancel()
      except Exception as exc:
          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" を返します。

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

   Added in version 3.7.

asyncio.all_tasks(loop=None)

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

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

   Added in version 3.7.

asyncio.iscoroutine(obj)

   Return "True" if *obj* is a coroutine object.

   Added in version 3.4.


Task オブジェクト
=================

class asyncio.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-only *context* argument allows specifying a
   custom "contextvars.Context" for the *coro* to run in. If no
   *context* is provided, the Task copies the current context and
   later runs its coroutine in the copied context.

   An optional keyword-only *eager_start* argument allows eagerly
   starting the execution of the "asyncio.Task" at task creation time.
   If set to "True" and the event loop is running, the task will start
   executing the coroutine immediately, until the first time the
   coroutine blocks. If the coroutine returns or raises without
   blocking, the task will be finished eagerly and will skip
   scheduling to the event loop.

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

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

   バージョン 3.10 で非推奨: Deprecation warning is emitted if *loop*
   is not specified and there is no running event loop.

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

   バージョン 3.12 で変更: Added the *eager_start* parameter.

   done()

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

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

   result()

      Task の結果を返します。

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

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

      If the Task's result isn't yet available, this method raises an
      "InvalidStateError" 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 モジュールと同じような出力を生成します。

      引数 *limit* は "get_stack()" にそのまま渡されます。

      The *file* argument is an I/O stream to which the output is
      written; by default output is written to "sys.stdout".

   get_coro()

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

      注釈:

        This will return "None" for Tasks which have already completed
        eagerly. See the Eager Task Factory.

      Added in version 3.8.

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

   get_context()

      Return the "contextvars.Context" object associated 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 already *done* or *cancelled*, return "False",
      otherwise, return "True".

      The method arranges for a "CancelledError" exception to be
      thrown into the wrapped coroutine on the next cycle of the event
      loop.

      The coroutine then has a chance to clean up or even deny the
      request by suppressing the exception with a "try" ... ...
      "except CancelledError" ... "finally" block. Therefore, unlike
      "Future.cancel()", "Task.cancel()" does not guarantee that the
      Task will be cancelled, although suppressing cancellation
      completely is not common and is actively discouraged.  Should
      the coroutine nevertheless decide to suppress the cancellation,
      it needs to call "Task.uncancel()" in addition to catching the
      exception.

      バージョン 3.9 で変更: Added the *msg* parameter.

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

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

         async def cancel_me():
             print('cancel_me(): before sleep')

             try:
                 # Wait for 1 hour
                 await asyncio.sleep(3600)
             except asyncio.CancelledError:
                 print('cancel_me(): cancel sleep')
                 raise
             finally:
                 print('cancel_me(): after sleep')

         async def main():
             # Create a "cancel_me" Task
             task = asyncio.create_task(cancel_me())

             # Wait for 1 second
             await asyncio.sleep(1)

             task.cancel()
             try:
                 await task
             except asyncio.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, further
      calls to "uncancel()" are ineffective.

      Added in version 3.11.

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

         async def make_request_with_timeout():
             try:
                 async with asyncio.timeout(1):
                     # Structured block affected by the timeout:
                     await make_request()
                     await make_another_request()
             except TimeoutError:
                 log("There was a timeout")
             # Outer code not affected by the timeout:
             await unrelated_code()

      While the block with "make_request()" and
      "make_another_request()" might get cancelled due to the timeout,
      "unrelated_code()" should continue running even in case of the
      timeout.  This is implemented with "uncancel()".  "TaskGroup"
      context managers use "uncancel()" in a similar fashion.

      If end-user code is, for some reason, suppressing cancellation
      by catching "CancelledError", it needs to call this method to
      remove the cancellation state.

      When this method decrements the cancellation count to zero, the
      method checks if a previous "cancel()" call had arranged for
      "CancelledError" to be thrown into the task. If it hasn't been
      thrown yet, that arrangement will be rescinded (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 to "cancel()" less the number of
      "uncancel()" calls.

      Note that if this number is greater than zero but the Task is
      still executing, "cancelled()" will still return "False". This
      is because this number can be lowered by calling "uncancel()",
      which can lead to the task not being cancelled after all if the
      cancellation requests go down to zero.

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

      Added in version 3.11.
