[docs] [issue24020] threading.local() must be run at module level (doc improvement)

Paul Moore report at bugs.python.org
Tue Apr 21 20:48:09 CEST 2015


Paul Moore added the comment:

That seems to merely be saying that each threading.local() object is distinct, so if you want to share threadlocal data between workers, creating local objects won't work.

I think I see what the confusion is (although I can't quite explain it yet, I'll need to think some more about it) but "threading.local() needs to be run at global scope" is not accurate (for example, if I understand correctly, a class attribute which is a threading.local value would work fine, and it's not "global scope".

Basically, each time you call threading.local() you get a brand new object. It looks like a dictionary, but in fact it's a *different* dictionary for each thread. Within one thread, though, you can have multiple threading.local() objects, and they are independent.

The "wrong" code in the SO discussion created a new threading-local() object as a local variable in a function, and tried to use it to remember state from one function call to the next (like a C static variable). That would be just as wrong in a single-threaded program where you used dict() instead of threading.local(), and for the same reasons.

I don't know what your code was doing, so it may well be that the problem you were encountering was more subtle than the one on the wont_work() function. But "threading.local() must be run in global scope" is *not* the answer (even if doing that resulted in your problem going away).

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue24020>
_______________________________________


More information about the docs mailing list