Consider the following code:
#/usr/bin/env python
from time import sleep
from random import random
from threading import Thread, local
data = local()
def bar():
print "I'm called from", data.v
def foo():
bar()
class T(Thread):
def run(self):
global data
sleep(random())
data.v = self.getName() # Thread-1 and Thread-2 accordingly
sleep(1)
foo()
>> T().start(); T().start()
I'm called from Thread-2
I'm called from Thread-1
Here threading.local() is used as a quick and dirty way to pass some data from run() to bar() without changing the interface of foo().
Note that using global variables won't do the trick:
#/usr/bin/env python
from time import sleep
from random import random
from threading import Thread
def bar():
global v
print "I'm called from", v
def foo():
bar()
class T(Thread):
def run(self):
global v
sleep(random())
v = self.getName() # Thread-1 and Thread-2 accordingly
sleep(1)
foo()
>> T().start(); T().start()
I'm called from Thread-2
I'm called from Thread-2
Meanwhile, if you could afford passing this data through as an argument of foo() - it would be a more elegant and well-designed way:
from threading import Thread
def bar(v):
print "I'm called from", v
def foo(v):
bar(v)
class T(Thread):
def run(self):
foo(self.getName())
But this is not always possible when using third-party or poorly designed code.