Ram Rachum
Ram Rachum

Reputation: 88708

Python: Getting all the items out of a `threading.local`

I have a threading.local object. When debugging, I want to get all the objects it contains for all threads, while I am only on one of those threads. How can I do that?

Upvotes: 7

Views: 1026

Answers (1)

dano
dano

Reputation: 94951

If you're using the pure-python version of threading.local (from _threading_local import local), this is possible:

for t in threading.enumerate():
    for item in t.__dict__:
       if isinstance(item, tuple):  # Each thread's `local` state is kept in a tuple stored in its __dict__
           print("Thread's local is %s" % t.__dict__[item])

Here's an example of it in action:

from _threading_local import local
import threading
import time

l = local()

def f():
   global l
   l.ok = "HMM"
   time.sleep(50)

if __name__ == "__main__":
    l.ok = 'hi'
    t = threading.Thread(target=f)
    t.start()
    for t in threading.enumerate():
        for item in t.__dict__:
           if isinstance(item, tuple):
               print("Thread's local is %s" % t.__dict__[item])

Output:

Thread's local is {'ok': 'hi'}
Thread's local is {'ok': 'HMM'}

This is exploiting the fact that the pure-python implementation of local stores each thread's local state in the Thread object's __dict__, using a tuple object as the key:

>>> threading.current_thread().__dict__
{ ..., ('_local__key', 'thread.local.140466266257288'): {'ok': 'hi'}, ...}

If you're using the implementation of local written in C (which is usually the case if you just use from threading import local), I'm not sure how/if you can do it.

Upvotes: 4

Related Questions