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

Thread-local data is data whose values are thread specific.

A local variable in a thread for example (x=10) is also thread specific.

What is the difference between using thread local and a local variable?

variable
  • 8,262
  • 9
  • 95
  • 215
  • A thread is not necessarily one single function, there can be multiple functions in a thread working with some shared data. – georg Jun 01 '21 at 11:13
  • The scope is different. Local variables stop to exist when the corresponding function returns. Did you read this? https://stackoverflow.com/questions/1408171/thread-local-storage-in-python – VPfB Jun 01 '21 at 11:35
  • The difference is that a local variable does not survive method scope but a thread-local variable does. – user207421 Jun 02 '21 at 12:13

1 Answers1

1

As always, it’s important to distinguish variables from objects. Each variable refers to an object (never another variable) and can in general be changed to refer to a different object; each object has some number of variables (e.g., dictionary entries, or attributes) and perhaps other data (like an integer’s value).

Every variable is associated with some object; local variables can be considered to be associated with a stack frame. A fortiori, a local variable is indeed specific to a thread, but a threading.local is an object (which can’t be thread-local) whose variables (attributes) are thread-local. Unlike a local variable, it is therefore possible to have a reference to a threading.local, so it can be shared among multiple users of an object (typically a module or an instance of a user-defined class). If those users are on different threads, each sees its own value for the associated variables (really, for the set of variables itself).

Davis Herring
  • 36,443
  • 4
  • 48
  • 76
  • I get your point about variables and object, but what I don't understand is why is there such a concept of `threading.local` when we can always create a variable (to hold any object) within a thread? What purpose does it serve? – variable Jun 02 '21 at 11:56
  • @variable: Do the last two sentences not help in that regard? – Davis Herring Jun 02 '21 at 13:11
  • Say I have a function FnX that will run in a thread. A variable declared in this function will be available to the entire function code. But the modules will be able to use this only via a function for example accepting this variable. So what you are saying is that - the threading local will be globally available in all the code running in the thread (like modules, etc). Have I got it right? – variable Jun 02 '21 at 13:57
  • 1
    @variable: That sounds about right: you can (perhaps “before your threads start”) create the thread-local object, publish it (perhaps as a module attribute, also known as a global variable), and then use it from multiple threads. – Davis Herring Jun 02 '21 at 14:53