Welcome, guest | Sign In | My Account | Store | Cart

Expands the idea from Thread-specific storage (by John E.Barham). ThreadedContext is like a dictionary, but stores its data in a private namespace for every thread.

Python, 36 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
ThreadedContext is like a dictionary, but stores its data in a private namespace for every thread.
A thread can't access to the data from other thread.
USAGE:
In Thread 1:
d = ThreadedContext()
d[1]=1

In Thread 2:
d[1] #raises KeyError exception
d[1]= 2

In Thread 1:
print d[1]	#prints 1

In Thread 2:
print d[1]	#prints 2
	
If a thread is deleted its keys in ThreadedContext are erased.
"""

from weakref import WeakKeyDictionary as _WeakKeyDictionary
from threading import currentThread as _currentThread

class ThreadedContext:
	def __init__(self):
		self.__thread_dict = _WeakKeyDictionary()
		
	def __getattr__(self,name):
		return getattr(self.__currentDict(),name)
		
	def __currentDict(self, _currentThread = _currentThread):
		try:
			return self.__thread_dict[_currentThread()]
		except KeyError:
			self.__thread_dict[_currentThread()] = result = {}
			return result

Use it when you need diferents namespace for every thread. For example: in a web server you can store HTTPRequest and HTTPResponse in a globally accesible ThreadedContext and do: httpRequest = context["HTTPRequest"] #context is a ThreadedContext instance.

1 comment

anthony baxter 19 years, 8 months ago  # | flag

Builtin to 2.4. In 2.4, use the threading.local object to get a thread-local storage.

Created by Andres Tuells on Thu, 13 Dec 2001 (PSF)
Python recipes (4591)
Andres Tuells's recipes (7)

Required Modules

  • (none specified)

Other Information and Tasks