Today I found myself thinking about a straightforward way of having “thread-local singletons”, that is, only one instance of a given class per thread. I don’t have a clear usercase for this, but I think it could be applied to something like a “one event loop per thread” concept, for example.
This can be done easily by saving an instance in a module level variable stored in a threading.local
container, but I wanted to explicitly try to create the object and always get the same instance back, assuming I’m on the same thread.
Here is the solution I came up with:
[gist]https://gist.github.com/1184190[/gist]
A metaclass is used to either create the new class instance or return the existing one from the thread-local storage. Since the class will only be instantiated once (the first time) I have chosen to ignore all initialization attributes, otherwise code would look very weird, because regardless of the initialization attributes, the same object would be returned. This could be improved by keeping a mapping between initialization attributes tuples and object instances, though.
Anyhow, this was a 5 minues quick-and-dirty hack, but do let me know if you hate it a lot :–)
:wq