how to make the function test() work correctly?
Python 3.4.1
a function into string does not work well when this string is inside a function. how define this function that inside a string?
def func(x):
return x+1
def test(a,b):
loc = {'a':a,'b':b}
glb = {}
exec('c = [func(a+i)for i in range(b)]', glb,loc)
c = loc['c']
print(c)
print('out the function test()')
a= 1
b= 4
c = [func(a+i)for i in range(b)]
print(c)
'''results:
out the function test()
[2, 3, 4, 5]
>>> test(1,4)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
test(1,4)
File "C:\Users\Rosania\Documents\Edilon\Python examples\apagar.py", line 6, in test
exec('c = [func(a+i)for i in range(b)]', glb,loc)
File "<string>", line 1, in <module>
File "<string>", line 1, in <listcomp>
NameError: name 'func' is not defined
'''
1 Answer 1
This is kind of evil to eval a string.
Assuming you know what you're doing...
Put "func" in the locals dict too. Your eval environments must know about everything you expect to reference in your eval'd string.
loc = {'a':a, 'b':b, 'func':func}
answered Jan 12, 2015 at 23:01
Chad Miller
1,4759 silver badges11 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Edilon Junior
did not work test(1,4) Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> test(1,4) File "C:\Users\Rosania\Documents\Edilon\Python examples\apagar.py", line 6, in test exec('c = [func(a+i)for i in range(b)]', glb,loc) File "<string>", line 1, in <module> File "<string>", line 1, in <listcomp> NameError: name 'func' is not defined >>>
Edilon Junior
maybe test() should be a class?
Edilon Junior
this is my true code, take a look: stackoverflow.com/questions/27913960/…
lang-py
glbshould be{'func': func}otherwise the string you'reexecing obviously gives that "name 'func' is not defined"NameErroryou report -- where did you think it could resolve that name?!