ポリシー

An event loop policy is a global object used to get and set the current event loop, as well as create new event loops. The default policy can be replaced with built-in alternatives to use different event loop implementations, or substituted by a custom policy that can override these behaviors.

The policy object gets and sets a separate event loop per context. This is per-thread by default, though custom policies could define context differently.

Custom event loop policies can control the behavior of get_event_loop(), set_event_loop(), and new_event_loop().

ポリシーオブジェクトは AbstractEventLoopPolicy 抽象基底クラスで定義された API を実装しなければなりません。

ポリシーの取得と設定

以下の関数は現在のプロセスに対するポリシーの取得や設定をするために使われます:

asyncio.get_event_loop_policy()

プロセス全体にわたる現在のポリシーを返します。

asyncio.set_event_loop_policy(policy)

プロセス全体にわたる現在のポリシーを policy に設定します。

policyNone の場合、デフォルトポリシーが現在のポリシーに戻されます。

ポリシーオブジェクト

イベントループポリシーの抽象基底クラスは以下のように定義されています:

class asyncio.AbstractEventLoopPolicy

asyncio ポリシーの抽象基底クラスです。

get_event_loop()

現在のコンテキストのイベントループを取得します。

AbstractEventLoop のインターフェースを実装したイベントループオブジェクトを返します。

このメソッドは None を返してはいけません。

バージョン 3.6 で変更.

set_event_loop(loop)

現在のコンテキストにイベントループ loop を設定します。

new_event_loop()

新しいイベントループオブジェクトを生成して返します。

このメソッドは None を返してはいけません。

asyncio は以下の組み込みポリシーを提供します:

class asyncio.DefaultEventLoopPolicy

デフォルトの asyncio ポリシーです。Unix では SelectorEventLoop 、Windows では ProactorEventLoop を使います。

デフォルトのポリシーを手動でインストールする必要はありません。 asyncio はデフォルトポリシーを使うように自動的に構成されます。

バージョン 3.8 で変更: Windows では ProactorEventLoop がデフォルトで使われるようになりました。

バージョン 3.12 で非推奨: The get_event_loop() method of the default asyncio policy now emits a DeprecationWarning if there is no current event loop set and it decides to create one. In some future Python release this will become an error.

class asyncio.WindowsSelectorEventLoopPolicy

SelectorEventLoop イベントループ実装を使った別のイベントループポリシーです。

利用可能な環境: Windows 。

class asyncio.WindowsProactorEventLoopPolicy

ProactorEventLoop イベントループ実装を使った別のイベントループポリシーです。

利用可能な環境: Windows 。

ポリシーのカスタマイズ

新しいイベントループのポリシーを実装するためには、以下に示すように DefaultEventLoopPolicy を継承して振る舞いを変更したいメソッドをオーバーライドすることが推奨されます。:

class MyEventLoopPolicy(asyncio.DefaultEventLoopPolicy):

    def get_event_loop(self):
        """Get the event loop.

        This may be None or an instance of EventLoop.
        """
        loop = super().get_event_loop()
        # Do something with loop ...
        return loop

asyncio.set_event_loop_policy(MyEventLoopPolicy())