如何清除 Python 的 threading.local()
实例的所有属性?
最佳答案
你可以清除它的底层__dict__
:
>>> l = threading.local()
>>> l
<thread._local object at 0x7fe8d5af5fb0>
>>> l.ok = "yes"
>>> l.__dict__
{'ok': 'yes'}
>>> l.__dict__.clear()
>>> l.__dict__
{}
>>> l.ok
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'thread._local' object has no attribute 'ok'
在 _threading_local
模块文档中,直接访问 __dict__
被明确称为与 local
对象交互的有效方式:
Thread-local objects support the management of thread-local data. If you have data that you want to be local to a thread, simply create a thread-local object and use its attributes:
>>> mydata = local() >>> mydata.number = 42 >>> mydata.number 42
You can also access the local-object's dictionary:
>>> mydata.__dict__ {'number': 42} >>> mydata.__dict__.setdefault('widgets', []) [] >>> mydata.widgets []
关于python - 如何清除 Python threading.local 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25693508/