[英]how new_event_loop work in asyncio python3
The code below is excerpted from events.py in package asyncio from python3.8.下面的代码摘自python3.8的package asyncio中的events.py。
Python use new_event_loop to create new loop, it return self._loop_factory(), but _loop_factory is just 'NoneType' object is not callable, how it works? Python 使用 new_event_loop 创建新循环,它返回 self._loop_factory(),但 _loop_factory 只是 'NoneType' object 不可调用,它是如何工作的?
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()
BaseDefaultEventLoopPolicy
is a base class. BaseDefaultEventLoopPolicy
是基础 class。 That attribute is set to something other than None
by the platform-specific classes such as _UnixDefaultEventLoopPolicy
, which inherit from BaseDefaultEventLoopPolicy
and make _loop_factory
a class attribute that's something callable :该属性被平台特定的类设置为
None
以外的东西,例如_UnixDefaultEventLoopPolicy
,它继承自BaseDefaultEventLoopPolicy
并使_loop_factory
成为 class 属性,这是可调用的:
class _UnixDefaultEventLoopPolicy(events.BaseDefaultEventLoopPolicy):
"""UNIX event loop policy with a watcher for child processes."""
_loop_factory = _UnixSelectorEventLoop
The base class could raise a NotImplementedError
if _loop_factory
is None, but it's possible that the authors wanted to avoid that overhead.如果
_loop_factory
为 None,则基础 class可能会引发NotImplementedError
,但作者可能希望避免这种开销。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.