Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I clear a Python threading.local object?

How can I clear all the attributes off an instance of Python's threading.local()?

like image 804
David Wolever Avatar asked Jul 26 '26 00:07

David Wolever


1 Answers

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
  []
like image 157
dano Avatar answered Jul 27 '26 14:07

dano