I cannot find the executed function even after the excution.
This is the function:
# function illustrating how exec() functions.
def exec_code():
LOC = """
def factorial(num):
fact=1
for i in range(1,num+1):
fact = fact*i
return fact
print(factorial(5))
"""
exec(LOC)
print(factorial)
# Driver Code
exec_code()
However, this yields an error:
NameError Traceback (most recent call last)
<ipython-input-10-d403750cbbfb> in <module>
13
14 # Driver Code
---> 15 exec_code()
<ipython-input-10-d403750cbbfb> in exec_code()
10 """
11 exec(LOC)
---> 12 print(factorial)
13
14 # Driver Code
NameError: name 'factorial' is not defined
I really would like to execute a string function as the above pattern. Does anyone know how to solve it? If exec is not recomanded, are there any other solutions?
According to the docs for exec(object[, globals[, locals]])
https://docs.python.org/3/library/functions.html#exec
Note The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns.
Therefore, you need to pass your own locals dict in as globals and locals:
mylocals = {}
exec(your_code, mylocals, mylocals)
Then you can call it through the mylocals:
print(mylocals['factorial']())