0

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?

ZHANG Juenjie
  • 501
  • 5
  • 20
  • Please read [mcve]. [Here's one I wrote](https://gist.github.com/wjandrea/4ae79ecd7f28f066e3ae6671c9f48fc1). You could use it if you'd like. – wjandrea Jun 22 '19 at 02:59

2 Answers2

1

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']())
gahooa
  • 131,293
  • 12
  • 98
  • 101
1

You can give globals() to the exec call to make it add the function to the current module:

exec(LOC,globals()) 
Alain T.
  • 40,517
  • 4
  • 31
  • 51