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

Eric Snow report at bugs.python.org
Tue Apr 21 21:11:41 CEST 2015


Eric Snow added the comment:

FYI, I've used thread-local namespaces with success in several different ways and none of them involved binding the thread-local namespace to global scope.  I don't think anything needs to be fixed here.

The SO answer is misleading and perhaps even wrong.  The problem it describes is about sharing the thread-local NS *between function calls*.  Persisting state between function calls is not a new or mysterious problem, nor unique to thread-local namespaces.  In the example they give, rather than a global they could have put it into a default arg or into a class:

def hi(threadlocal=threading.local()):
    ...

class Hi:
    threadlocal = threading.local()
    def __call__(self):
        ...  # change threadlocal to self.threadlocal

hi = Hi()

This is simply a consequence of Python's normal scoping rules (should be unsurprising) and the fact that threading.local is a class (new instance per call) rather than a function (with the assumption of a singleton namespace per thread).

At most the docs could be a little more clear that threading.local() produces a new namespace each time.  However, I don't think even that is necessary and suggest closing this as won't fix.

----------
nosy: +eric.snow

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


More information about the docs mailing list