0

I have some python (2.7) code using exec() :

import math

def some_function(a, b):
    return a+b

safe_dict = { 'Sqrt': math.sqrt, 'Smurf': some_function, "__builtins__": None }
with open('my_file.py') as f:
    exec(f.read(), safe_dict, {})

print('The End')

And "my_file.py" is: print('in exec script')

print('sqrt(2) = %f' % Sqrt(2)) # Call to math.sqrt     through name 'Sqrt'  given in globals
print('3+4 = %d' % Smurf(3, 4)) # Call to some_function through name 'Smurf' given in globals

def my_func(x):
    return Sqrt(2+x)
print("my_func: %f" % my_func(1))   # No problems

def my_func2(x, f):
    return f(x-1)
print("my_func2: %f" % my_func2(5, my_func))   # No problems too

def my_func3(x):
    return my_func(x-1) # Here, leads to a "NameError: global name 'my_func' is not defined" in the next line
print("my_func3: %f" % my_func3(5))

I don't understand why there is a NameError in my_func3 when it tries to call my_func.

Why my_func3 is not able to call my_func, even if previously defined ?

Is there a way to make it work (not with my_func defined in the main module) ?

edit Error is:

Traceback (most recent call last):
  File "main.py", line 9, in <module>
    exec(f.read(), safe_dict, {})
  File "<string>", line 16, in <module>
  File "<string>", line 15, in my_func3
NameError: global name 'my_func' is not defined
Chandella07
  • 2,089
  • 14
  • 22
doomyster
  • 123
  • 1
  • 8
  • show the real error message – Vicrobot Sep 13 '18 at 16:02
  • 1
    Errors aside, almost certainly your approach is not safe, checkout this post and elegant solution https://stackoverflow.com/a/9558001/6260170 – Chris_Rands Sep 13 '18 at 16:03
  • Don't use this approach, but the problem is that you are providing both a globals and locals dict. Since that is the case, the code is executed as if it were embedded in a class definition. – juanpa.arrivillaga Sep 13 '18 at 16:46
  • 1
    `exec(f.read(), safe_dict, safe_dict)` will make it work and you can find the explanation in [this post](https://stackoverflow.com/questions/2904274/globals-and-locals-in-python-exec) – Canh Sep 13 '18 at 16:57
  • @juanpa.arrivillaga and Canh: thank both of you. I better understand why it didn't work. If you were to make an answer, I would accept it. – doomyster Sep 17 '18 at 08:48

0 Answers0