为什么 threading.Event 是函数而不是 class?

Why is threading.Event a function instead of class?

对于我正在处理的项目,我们使用 python 2.7。 我需要在两个踏板之间实现同步,一个发出信号,另一个等待。所以我为此目的使用了 threading.Event 的实例。我通过它的构造函数将这个事件对象注入到另一个对象(可以说是 AnotherClass 的实例)中。在 AnotherClass 的构造函数中,我想验证输入参数,所以我检查了它的类型是否实际上是 threading.Event 的实例。这是我感到惊讶的地方,因为它失败了。

代码看起来像这样:

from threading import Event

class AnotherClass(object):
    def __init__(self, event):
        if not isinstance(event, Event):
            raise ValueError("event is not instance of threading.Event"):
    ...

event = Event()
another_object = AnotherClass(event) # raises exception

当我开始调试问题时,我发现 threading.Event 实际上是一个 returns 实例 threading._Event class:

的函数
>>> from threading import Event
>>> Event
<function Event at 0x0000000002B529E8>
>>> e = Event()
>>> e
<threading._Event object at 0x0000000002AE0358>

在 python 文档页面上声明它是 class。 这对我来说似乎不合逻辑。例如,情况并非如此。 threading.Thread。它实际上是一个 class 并且它有构造函数:

>>> Thread
<class 'threading.Thread'>
>>> dir(Thread)
['_Thread__bootstrap', '_Thread__bootstrap_inner', '_Thread__delete', '_Thread__exc_clear', '_Thread__exc_info', '_Thread__initialized', '_Thread__stop', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_block', '_note', '_reset_internal_locks', '_set_daemon', '_set_ident', 'daemon', 'getName', 'ident', 'isAlive', 'isDaemon', 'is_alive', 'join', 'name', 'run', 'setDaemon', 'setName', 'start']

当然,我可以省略这个检查,让代码稍后在传递的对象上调用一些不存在的方法时失败,但我希望这段代码尽快失败。

所以,总结一下我的问题:

谁能解释一下 threading.Event 的实现背后的原因是什么?

我不知道在线文档是怎么回事,但您发布的屏幕截图是针对 class threading._Event,尽管它说它是针对 class threading.Eventthreading.Event 是一个工厂函数,它 returns 是 threading._Event 的一个实例。我认为这是非常不直观的,特别是因为文档没有在 threading.Eventthreading._Event 之间进行印刷区分,你是对的。 https://docs.python.org/2.7/library/threading.html#module-threading 页面上说 threading.Event 是一个工厂函数(正确),它还说要查看“事件对象”,它们实际上是 class threading._Event,在文档中被错误地描述为class threading.Event.

我进行了一些谷歌搜索,看起来文档已经以这种方式被破坏了很多年。

线程事件在 Python.

的更高版本中被明智地创建