Reputation: 154634
How can I clear all the attributes off an instance of Python's threading.local()
?
Upvotes: 6
Views: 3522
Reputation: 94951
You can clear it's underlying __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'
Accessing the __dict__
directly is specifically called out as a valid way to interact with the local
object in the _threading_local
module documentation:
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 []
Upvotes: 10