【发布时间】: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