Casebash Casebash - 1 year ago 147
Python Question

Thread local storage in Python

How do I use thread local storage in Python?


Answer Source

As noted in the question, Alex Martelli gives a solution here. This function allows us to use a factory function to generate a default value for each thread.

#Code originally posted by Alex Martelli
#Modified to use standard Python variable name conventions
import threading
threadlocal = threading.local()    

def threadlocal_var(varname, factory, *args, **kwargs):
  v = getattr(threadlocal, varname, None)
  if v is None:
    v = factory(*args, **kwargs)
    setattr(threadlocal, varname, v)
  return v
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download