Edilon Junior
Edilon Junior

Reputation: 9

execute string with function into a function

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

'''

Upvotes: 0

Views: 67

Answers (1)

Chad Miller
Chad Miller

Reputation: 1475

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}

Upvotes: 2

Related Questions