UPDATE: Sorry I was wrong with my assumption of the problem. Its due to me trying to make the function parallel and have multiple proceses change the same dictionary. How can I design my function so it allows for this? If I have to send the dictionary(in this case) then it'll keep overwriting itself and can't span over all the cores. I'm happy to redesign the function but not sure how i can do it and still spread it over multiple cores.
To simplify, I basically have something like the following:
list = [1,2,3,10]
dictionary = {}
for x in list:
for xx in range(100):
for xxx in range(100):
dictionary[x]=xx*xxx
This works, but when I wrap the for loop in a function, I get: NameError: global name 'dictionary' is not defined
def test(x):
for xx in range(100):
for xxx in range(100):
dictionary[x]=xx*xxx
I know this has something to do with the namespace but I don't want to send variables to the function in this case because I think it'll overwrite the variable dictionary. How can I reference the dictionary variable while in the function? The reason I ask is I want to create a process that spans multiple cpu's, so I don't want to declare the variables in each function.
I'm using functions but if I need to use classes or there's another way to get around this then please me know and I'll rethink my approach.
3 Answers 3
Try again:
lst = [1,2,3,10]
dictionary = {}
def test(x):
for xx in range(100):
for xxx in range(100):
dictionary[x]=xx*xxx
for x in lst:
test(x)
You only get a NameError when a name is not defined. It has nothing to do with scopes.
1 Comment
How can I reference a outside variable from within a function?
Don't. Pass it as a parameter.
4 Comments
Try to avoid global variables and pass the variables needed into the function:
>>> def test(x, dictionary):
... for xx in range(100):
... for xxx in range(100):
... dictionary[x] = xx * xxx
...
>>> list_of_numbers = [1, 2, 3, 10]
>>> dictionary = {}
>>>
>>> for x in list_of_numbers:
... test(x, dictionary)
...
>>> print dictionary
{1: 9801, 2: 9801, 3: 9801, 10: 9801}
I've renamed list, since it is a Python built-in.
This can clearly be simplified to:
>>> for x in list_of_numbers:
... dictionary[x] = 99 * 99