I have a piece of code stored in a string (user edits this in a text box in my application). In this code, there is a function which I want to run later using multiprocess.Pool
. But it does not work if the functions defined in the string are nested.
Note that I am using multiprocess
, rather than standard multiprocessing
, which would not be able to run the functions defined in the string at all.
See the comments in the following snippet to see what happens. Is there any workaround which I could use in my scenario?
funcs = """
def func(x):
return func_inner(x) + 1
def func_inner(x):
return x + 1
"""
import multiprocess
if __name__ == "__main__":
symbols = dict()
exec(funcs, symbols)
func = symbols["func"]
print(func(1)) # this is evaluated correctly as 3 so nesting functions work fine!
data = [1, 2, 3]
pool = multiprocess.Pool()
print(pool.map(func, data)) # this fails with NameError: name 'func_inner' is not defined!
I tried this on Windows and Linux as well. My multiprocess
version is 0.70.5 and Python 3.5.