Chris Kirkland

Software Engineer / Math Nerd / Barbershop Enthusiast

Python "Thread-locality"

Python threading module and thread-local objects The __init__() body of Python threading.Threads runs in the main thread. Any Thread-local setup must be done inside of the threading.Thread.run() body; for example, SQLAlchemy`s thread-local scoped_session must be invoked inside of each thread to avoid conflicts/race conditions/etc. Here is a simple example: ### threading-example.py (python 2.6+) from threading import Thread, current_thread class BadThread(Thread): def __init__(self): Thread.__init__(self) self.current_thread = current_thread() def run(self): pass class GoodThread(Thread): def __init__(self): Thread.