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

2024/10/12 0:25:02

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?

Answer

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 timel = local()def f():global ll.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.

https://en.xdnf.cn/q/69715.html

Related Q&A

Why tuple is not mutable in Python? [duplicate]

This question already has answers here:Closed 11 years ago.Possible Duplicate:Why are python strings and tuples are made immutable? What lower-level design makes tuple not mutable in Python? Why th…

Display Django form fields on the same line

I would like to display two form fields on the same line and not each one after the other one.For the moment, I get:Choice a theme :. Datasystems. CamerounBut I would like to display this form like:Cho…

How can I use the index array in tensorflow?

If given a matrix a with shape (5,3) and index array b with shape (5,), we can easily get the corresponding vector c through,c = a[np.arange(5), b]However, I cannot do the same thing with tensorflow,a …

cython with array of pointers

I have a list of numpy.ndarrays (with different length) in python and need to have very fast access to those in python. I think an array of pointers would do the trick. I tried:float_type_t* list_of_ar…

How to skip blank lines with read_fwf in pandas?

I use pandas.read_fwf() function in Python pandas 0.19.2 to read a file fwf.txt that has the following content:# Column1 Column2123 abc456 def# #My code is the following:import pandas as pd fil…

Pandas rolling std yields inconsistent results and differs from values.std

Using pandas v1.0.1 and numpy 1.18.1, I want to calculate the rolling mean and std with different window sizes on a time series. In the data I am working with, the values can be constant for some subse…

How to change attributes of a networkx / matplotlib graph drawing?

NetworkX includes functions for drawing a graph using matplotlib. This is an example using the great IPython Notebook (started with ipython3 notebook --pylab inline):Nice, for a start. But how can I in…

Deploying MLflow Model without Conda environment

Currently working on deploying my MLflow Model in a Docker container. The Docker container is set up with all the necessary dependencies for the model so it seems redundant for MLflow to also then crea…

Insert Data to SQL Server Table using pymssql

I am trying to write the data frame into the SQL Server Table. My code:conn = pymssql.connect(host="Dev02", database="DEVDb") cur = conn.cursor() query = "INSERT INTO dbo.SCORE…

module object has no attribute discover_devices

Im trying to get Pybluez to work for me. Here is what happens when I try to discover bluetooth devises. import bluetooth nearby_devices = bluetooth.discover_devices()Traceback (most recent call last):F…