from multiprocessing import Pool
import random
results = []
def f(t):
return t
def cb_append_result(t):
# reports "local variable 'results' referenced before assignment"
# results += [t]
# Okay
results.append(t) # works
if __name__ == '__main__':
pool = Pool()
t = random.random()
pool.apply_async(f,args=(t,),callback=cb_append_result)
pool.close()
pool.join()
print("Result is {}".format(results))
(补充)该问题与多处理或回调无关(请参阅下面的答案)。但要解决上述问题,回调函数应编写为
def cb_append_result(t):
global results
results += [t]
y = []
# doesn't work
def f(x):
y += [x]
# works
def g(x):
global y # <===== Answer!!
y += [x]
# works
def h(x):
y.append(x)
# f(1) # local variable 'y' referenced before assignment
g(1) # works
print(y)
h(2) # works
print(y)