10

How can you use the python exec keyword inside functions?

3 Answers3

19

It's going to damage your function's performance, as well as its maintainability, but if you really want to make your own code so much worse, Python2 (this will not work in Python3, there you need to use the second alternative) gives you "enough rope to shoot yourself in the foot" (;-):

>>> def horror():
...   exec "x=23"
...   return x
... 
>>> print horror()
23

A tad less horrible, of course, would be to exec in a specific dict:

>>> def better():
...   d = {}
...   exec "x=23" in d
...   return d['x']
... 
>>> print better()
23

This at least avoids the namespace-pollution of the first approach.

Thomas
  • 1,823
  • 1
  • 8
  • 24
Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • 3
    Sometimes I need to make variables on the fly while doing some symbolic computing. How else do you suggest to do this, without using exec? – imranal Jul 19 '18 at 19:25
  • @imranal i need exactly this in my code and the only way I also found was using 'exec'. Did you find any other option ever since – taiko Aug 11 '20 at 19:47
  • worst example of exec() use I've ever seen – Vaidøtas I. Nov 05 '20 at 20:02
7

Alex's answer works slightly differently in Python 3.

Since exec() is a function in Python 3, use the following pattern-

def better():
    d = {}
    exec("x=23", d)
    return d['x']

print better()
23

See this question for more details- Behavior of exec function in Python 2 and Python 3

H. Saxena
  • 335
  • 4
  • 11
  • 1
    Is there a solution for python3 that doesn't involve creating a dictionary? – Nic Scozzaro Apr 19 '19 at 19:38
  • 4
    Use `exec('x=23', globals())` but note that this will add all variables generated inside exec into your global scope. It'll also overwrite any variables with the same name. – H. Saxena Apr 21 '19 at 02:13
  • The `exec(code_string, globals())` was exactly what I needed to import and use functions from interactively. Thanks @H.Saxena! – vpz Feb 02 '22 at 19:03
0

Yes.

class A:
    def __init__(self):
        self.a1 = ''
        self.a2 = ''

def populate():
    att1 = raw_input("enter a1: ")
    att2 = raw_input("enter a2: ")
    my_object = A()
    eval("my_obj.a1 = att1")
    eval("my_obj.a2 = att2")
    if eval("my_obj.a2") == 2:
    print "Hooray! the value of a2 in my_obj is 2"

Hope this helps

inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
  • 1
    eval and exec, two different things in Python. eval("my_obj.a1 = att1") will give you a syntax error (raised by eval) (try exec instead). – Ponkadoodle Apr 13 '10 at 02:34
  • `eval()` in Python only accepts expressions, and assignment is a statement, not an expression. – Greg Hewgill Apr 13 '10 at 02:34
  • I'm sorry. I clearly made a bad post. I see the error now and realize that I made an idiot move. I guess the exam stress must be getting to me. Apologies. – inspectorG4dget Apr 13 '10 at 04:35