Darragh Long
Darragh Long

Reputation: 23

Python - imported function doesn't modify local variable

I have a python script (myscript.py)that contains a number of funtions, and a global variable called 'resultsdict' (an empty dictionary). I want to reuse one of those functions (myfunc).

myfunc takes a single input (input), creates a dictionary (tempdict), and then updates resultsdict (key = input, value = tempdict). I generally use this function by looping through a list, calling each member of the list as input.

resultsdict = {}
mylist = [1,2,3]
for x in mylist:
    myfunc(x)
print(resultsdict)
{1:{dict of results-1},2:{dict of results-2},3:{dict of results-3}}

I want to reuse myfunc in a second script (script2.py). script2.py also contains a global variable called resultsdict. When I import myfunc to script2 and run it , the resultsdict variable isn't updated.

from myscript import myfunc
resultsdict = {}
mylist = [1,2,3]
for x in mylist:
    myfunc(x)
print(resultsdict)
{}

Any help would be greatly appreciated

Upvotes: 0

Views: 255

Answers (3)

Reyhaneh Torab
Reyhaneh Torab

Reputation: 367

in your for statement, you use "list" but in the line before that, you declare "mylist" !! Note: there is no "list" and thats why your code does not work.

Edit your for statement like below:

for x in my mylist:
    ...

Upvotes: 0

Sima
Sima

Reputation: 122

I guess you modify resultsdict from global scope in your myfunc. Try change this behavior to transfer resultsdict via attributes:

def myfync(x, resultsdict):
...

or add line about that resultsdict is from global scope(worse way):

def myfync(x):
    global resultsdict
...

and in any way modify mutable object in some function is bad way.

Upvotes: 1

abhilb
abhilb

Reputation: 5757

import the resultsdict too. Then if you want make a copy.

from myscript import myfunc, resultsdict

mylist = [1,2,3]
for x in mylist:
    myfunc(x)
print(resultsdict)

Upvotes: 0

Related Questions