【问题标题】:assert variable is threading._Event protected class instance断言变量是 threading._Event 受保护的类实例
【发布时间】:2017-06-18 13:39:36
【问题描述】:

我想检查变量e 是否是threading.Event 的实例。但是,当我创建e 时,它实际上创建了一个受保护的类实例threading._Event。例如:

import threading
e = threading.Event()
assert type(e) == threading.Event   # raises AssertionError
assert type(e) == threading._Event  # succeeds

断言它是一个受保护的类实例似乎不是pythonic。 assert type(e) == type(threading.Event()) 会更好吗?其他选择会更好吗?

【问题讨论】:

  • threading.Event 不是一个类。文档将其描述为工厂函数。
  • ...哦,该死的,这是另一个文档冲突的案例。文档的某些部分实际上确实将其称为类。至少 3.3+ 的文档是正确的(因为那时它实际上变成了一个类)。
  • 如果您想执行显式类型检查,我会使用 type(threading.Event()) 并将其保存到变量中。
  • assert type(e) == threading.Event 在 Python 3 中有效,但 assert type(e) == threading._Event 不能(_Event 无法识别)
  • @user2357112 为什么要将它保存到变量中,而不是像我的示例中那样使用并删除它?

标签: assert python-2.x python-multithreading


【解决方案1】:

看看at this answer about subclassing threading.Event

threading.Event 不是一个类,它是 threading.py 中的函数

def Event(*args, **kwargs): """A factory function that returns a new event. Events manage a flag that can be set to true with the set() method and reset to false with the clear() method. The wait() method blocks until the flag is true. """ return _Event(*args, **kwargs)

由于此函数返回 _Event 实例,您可以将 _Event 子类化(尽管导入和使用带下划线的名称从来都不是一个好主意):

from threading import _Event class State(_Event): def __init__(self, name): super(Event, self).__init__() self.name = name def __repr__(self): return self.name + ' / ' + self.is_set()

这在 Python 3 中已更改:

class Event: """Class implementing event objects. Events manage a flag that can be set to true with the set() method and reset to false with the clear() method. The wait() method blocks until the flag is true. The flag is initially false. """

【讨论】:

    猜你喜欢
    • 2018-08-19
    • 2015-04-08
    • 2013-12-05
    • 2013-09-04
    • 1970-01-01
    • 1970-01-01
    • 2012-03-03
    • 2021-10-04
    • 2011-08-02
    相关资源
    最近更新 更多