0

There are already questions that address this problem, e.g.

Python: 'thread._local object has no attribute 'todo'

But the solutions doesn't seem to apply to my problem. I make sure to access threding.local() in the same thread that sets the value. I'm trying to use this feature in conjuction with socket server. This is my code

class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):
    def handle(self):
        token = str(uuid4())
        global_data = threading.local()
        global_data.token = token
        logger.info(f"threading.local().token: {threading.local().token}")  # This line raises the error

The server code I'm using:

class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
    pass


def run_server():
    server = ThreadedTCPServer(
        (definitions.HOST, definitions.PORT), ThreadedTCPRequestHandler
    )
    with server:
        server.serve_forever()
J.Horcasitas
  • 167
  • 2
  • 8

1 Answers1

1

Your code does this:

  1. Create a brand new threading.local
  2. Store a reference to it in the variable global_data
  3. Give it a token
  4. Create a brand new threading.local
  5. Print its token

Step 5 throws an exception because the new threading.local you created in step 4 does not have a token because it is not the same threading.local you created in step 1.

Perhaps you meant {global_data.token}?

user253751
  • 57,427
  • 7
  • 48
  • 90
  • Thank you for the answer. My understanding was that for every thread a single threading.local() was returned. As stated in the official documentation https://docs.python.org/3/library/threading.html#thread-local-data "The instance’s values will be different for separate threads.". So I assume that for the same thread the instance's values will be the same. – J.Horcasitas Jul 19 '22 at 02:37
  • I believed that threading.local worked as flask g i.e. as a way to store variables accessible from everywhere as long as it was the same thread. If this is not the case, do you know how can I achive this? – J.Horcasitas Jul 19 '22 at 02:38
  • Your answer make me investigate this. I found this answer https://stackoverflow.com/questions/1408171/thread-local-storage-in-python which states that "One important thing that is easily overlooked: a threading.local() object only needs to be created once, not once per thread nor once per function call." So I believe this is the problem. I'm gonna see if this solutions works. Thanks again – J.Horcasitas Jul 19 '22 at 02:43
  • @J.Horcasitas It says **the instance's values**. Your code makes two instances. – user253751 Jul 19 '22 at 10:46
  • Just to confirm that this was in fact the problem. The solution was to create the threading local storage just one time at start up. – J.Horcasitas Jul 23 '22 at 05:12