`threading.local()` questions

BTW Ken, what I implemented and was asking about in the other thread was based on your answer in this thread. My implementation uses the execute_wrapper design paradigm from the Database Instrumentation page you linked me to above. It wraps every SQL execution in the wrapper provided using context managers. I essentially did the same thing, but instead of wrapping database executions, I wrapped model object instantiations. I would have wrapped just the save/delete calls, but that made it too complex.

The difference was that I couldn’t quite follow (or don’t remember) where the context stack of connection wrappers was stored. And the threading used was different from threading.local(), so I tried to work it out with threading.local on my own. I put my context stack in a class attribute.

But I had assumed incorrectly that when a class(/type) is created, it is done on each thread. I think that my mistake was that the class(/type) is in shared memory, so it’s only setting the thread variables once (for the current thread).

I could try and maintain the stack somewhere other than as a class attribute, but I still have to be thread-safe, so even if I put it somewhere else (that is not akin to a global variable), it needs to have different distinct states based on thread.

Thanks to your insights on the other thread, I know the direction I need to go. And again, I appreciate your invaluable help.