【问题标题】:how new_event_loop work in asyncio python3new_event_loop 如何在 asyncio python3 中工作
【发布时间】:2021-01-26 01:56:49
【问题描述】:

以下代码摘自python3.8的asyncio包中的events.py。

Python 使用 new_event_loop 创建新循环,它返回 self._loop_factory(),但 _loop_factory 只是 'NoneType' 对象不可调用,它是如何工作的?

class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy):

    _loop_factory = None

    class _Local(threading.local):
        _loop = None
        _set_called = False

    def __init__(self):
        self._local = self._Local()

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

        Returns an instance of EventLoop or raises an exception.
        """
        if (self._local._loop is None and
                not self._local._set_called and
                isinstance(threading.current_thread(), threading._MainThread)):
            self.set_event_loop(self.new_event_loop())

        if self._local._loop is None:
            raise RuntimeError('There is no current event loop in thread %r.'
                               % threading.current_thread().name)

        return self._local._loop

    def set_event_loop(self, loop):
        """Set the event loop."""
        self._local._set_called = True
        assert loop is None or isinstance(loop, AbstractEventLoop)
        self._local._loop = loop

    def new_event_loop(self):
        """Create a new event loop.

        You must call set_event_loop() to make this the current event
        loop.
        """
        return self._loop_factory()

【问题讨论】:

    标签: python python-asyncio


    【解决方案1】:

    BaseDefaultEventLoopPolicy 是一个基类。该属性被特定于平台的类(例如 _UnixDefaultEventLoopPolicy)设置为 None 以外的其他值,这些类继承自 BaseDefaultEventLoopPolicymake _loop_factory a class attribute that's something callable

    class _UnixDefaultEventLoopPolicy(events.BaseDefaultEventLoopPolicy):
        """UNIX event loop policy with a watcher for child processes."""
        _loop_factory = _UnixSelectorEventLoop
    

    如果_loop_factory 为None,则基类可以引发NotImplementedError,但作者可能希望避免这种开销。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-06
      相关资源
      最近更新 更多