정책

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 정책. 유닉스에서는 SelectorEventLoop를, 윈도우에서는 ProactorEventLoop를 사용합니다.

수동으로 기본 정책을 설치할 필요는 없습니다. asyncio는 기본 정책을 자동으로 사용하도록 구성됩니다.

버전 3.8에서 변경: 윈도우에서, 이제 기본적으로 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 이벤트 루프 구현을 사용하는 대안 이벤트 루프 정책.

가용성: 윈도우.

class asyncio.WindowsProactorEventLoopPolicy

ProactorEventLoop 이벤트 루프 구현을 사용하는 대안 이벤트 루프 정책.

가용성: 윈도우.

사용자 정의 정책

새로운 이벤트 루프 정책을 구현하려면, 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())