简体   繁体   中英

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

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.

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:
    ...

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM