0

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

'''

2
  • 1
    What in the blue blazes are you actually trying to do, and why? Commented Jan 12, 2015 at 23:01
  • At the very least, your glb should be {'func': func} otherwise the string you're execing obviously gives that "name 'func' is not defined" NameError you report -- where did you think it could resolve that name?! Commented Jan 12, 2015 at 23:02

1 Answer 1

2

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}
Sign up to request clarification or add additional context in comments.

3 Comments

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 >>>
maybe test() should be a class?
this is my true code, take a look: stackoverflow.com/questions/27913960/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.