variable
variable

Reputation: 9724

What is the difference (in terms of its purpose) between using thread local and a local variable?

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?

Upvotes: 2

Views: 285

Answers (1)

Davis Herring
Davis Herring

Reputation: 40013

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).

Upvotes: 1

Related Questions