Reputation: 11
I have a function in my main program that attempts to retrieve information from an imported module, which is a different script I wrote. This module spits out a variable which I access from the main program by making it a global.
However, since I'm threading the function that requests the information, the global variable gets polluted by adding the information from separate requests into one var. What I'm looking for is a way to access a local variable in a function in a module.
Main program:
import module
def threaded_function():
module.function(var1, var2)
print module.output
Module:
def function(var1, var2):
global output
output = []
DoThingsWithVars(var1, var2)
output.append(result)
Since the threading causes it to get accessed multiple times I figured I'd not use global variables and get the local variables for each request. Any idea how I can get at those?
Upvotes: 1
Views: 1557
Reputation: 11315
Well, the only cases when func locals makes sense are closures and generators. You can access them via __closure__
attribute, but you would have to spawn closure for each separate thread, and it would be easier to just pass thread-local list to function instead.
Other approach, which is actually used sometimes, is to have thread-local globals. Read http://docs.python.org/library/threading.html#threading.local for details. In your case it would work like this:
locs = threading.local()
def function(var1, var2):
global locs
if not locs.output:
locs.output = []
DoThingsWithVars(var1, var2)
locs.output.append(result)
Upvotes: 2