下面的代码摘自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()发布于 2021-01-26 10:17:08
BaseDefaultEventLoopPolicy是一个基类。该属性由特定于平台的类(如从BaseDefaultEventLoopPolicy和make _loop_factory a class attribute that's something callable继承的_UnixDefaultEventLoopPolicy )设置为None以外的值
class _UnixDefaultEventLoopPolicy(events.BaseDefaultEventLoopPolicy):
"""UNIX event loop policy with a watcher for child processes."""
_loop_factory = _UnixSelectorEventLoop如果_loop_factory为None,则基类可以引发NotImplementedError,但作者可能希望避免该开销。
https://stackoverflow.com/questions/65894914
复制相似问题