FYI, just caught myself on this, so I write this for all those Java -> Python types out there. In Python 2.4, there is a new class in threading called local, which acts as thread local storage. This was one of the features I was patiently waiting for Python to acquire, only to find out it didn’t work! At least it didn’t work for me, that is. I expected threading.local() to return a singleton thread local storage object attached to the current thread. It does not. It does not return a singleton. Example:
>>> import threading
>>> x=threading.local()
>>> x.test=42
>>> x.test
42
>>> x.__dict__
{’test’: 42}
>>> y = threading.local()
>>> y.__dict__
{}
>>> y.test
Traceback (most recent call last):
File “<stdin>”, line 1, in ?
AttributeError: ‘thread._local’ object has no attribute ‘test’
>>>
>>> x=threading.local()
>>> x.test=42
>>> x.test
42
>>> x.__dict__
{’test’: 42}
>>> y = threading.local()
>>> y.__dict__
{}
>>> y.test
Traceback (most recent call last):
File “<stdin>”, line 1, in ?
AttributeError: ‘thread._local’ object has no attribute ‘test’
>>>
I fully expected y to equal x, and it clearly does not. I suppose that this will bite many Python programmers converting from Java, so I thought I would share it with everyone.
Popularity: 32%
Comments: (4)