Python Threading

Thread local storage in Python

Thread-local storage is a useful method for storing data that is only accessible in the current thread.

import threading
mydata = threading.local()
mydata.x = 1

For convenience, we can set a factory function to be used as the default value (code by Alex Martelli)

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

This page contains content under license from

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License