9
votes

I am trying to run this code but it seems that the exec() is not executing the string inside the function:

def abc(xyz):
    for i in fn_lst:
        s = 'temp=' + i + '(xyz)'
        exec(s)
        print (temp)

abc('avdfbafadnf')

The error I am receiving:

NameError                                 Traceback (most recent call last)
<ipython-input-23-099995c31c78> in <module>()
----> 1 abc('avdfbafadnf')

<ipython-input-21-80dc547cb34f> in abc(xyz)
      4         s = 'temp=' + i + '(word)'
      5         exec(s)
----> 6         print (temp)

NameError: name 'temp' is not defined

fn_lst is a list of function names i.e: ['has_at', 'has_num' ...]

Please let me know an alternative to exec() if possible in such a scenario.

4
The correct answer, is to include locals(), and/or globals() in the argument list, so that the result will be part of the scope outside of the exec() call. See my answer for an example of how to do this. - DrM

4 Answers

0
votes

Instead of using exec with function names, just keep the function objects in the list:

fn_lst = [has_at, has_num, ...]

and perform the call directly:

def abc(xyz):
    for i in fn_lst:
        temp= i(xyz)
        print(temp)
8
votes

To make a variable set by the string passed to exec(), available outside of the call, use exec() like this:

exec( a_string, globals(), locals() )

For example,

exec( 'a = 3', globals(), locals() )

print( a )

will print the following result:

3

Note: In this example it would have been sufficient to use locals() alone, i.e. omitting globals(). Both were included here to illustrate the more general case. The use of locals() and/or globals() is part of a larger topic, known as "Scope". You can read more about this at Python Textbook - Scope

6
votes

I don't have enough reputation points to add comments, but I would like to mention that the previous answer by DrM does not work (inside a function):

def test():
    exec( 'a = 3', globals(), locals() )
    print(a)
test()

This code gives an error in Python 3:

NameError: name 'a' is not defined

I tried some methods using the compile function suggested in other forums, but they still do not work for me (at least with the options I have seen mentioned).

According to my research, this the closest code that I have seen working:

def test():
    lcls = locals()
    exec( 'a = 3', globals(), lcls )
    a = lcls["a"]
    print(f'a is {a}')
test()

It successfully prints:

a is 3

I think this is an important topic overall. Sometimes when you work with symbolic algebra libraries, like Sympy, defining variables though the exec function can be very convenient for Scientific Computing.

I hope somebody knows a good answer to the problem.

3
votes

After spending so much time doing hit and trial on this problem, I can say that using exec like this was working without any problem inside function, otherwise it threw error. I have tested this for both functions and variables.

def main():
  x = "def y():\n\treturn('This will work')"
  #pass only globals() not locals()
  exec(x,globals())
  print(y())
  
main()

def test():
    #pass only globals() not locals()
    exec( 'a = 3', globals())
    print(a)
test()

Here is a screenshot of this working on W3School's online interpreter (you can copy/paste and test it here yourself) enter image description here