views:

169

answers:

3

How can you use the python exec keyword inside functions?

+6  A: 

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, Python 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.

Alex Martelli
Running inside a dictionary made it work. Thans
None
A: 

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
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).
Wallacoloo
`eval()` in Python only accepts expressions, and assignment is a statement, not an expression.
Greg Hewgill
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
A: 

Sorry, I was unclear. I am building a Tkinter app in python on a mac that runs python code. It gets input from an Entry when a button is pressed. This is the error:

exec text
SyntaxError: unqualified exec is not allowed in function 'run' it is a nested function

how can I fix this.

None
Fixed. I executed the code in a dictionary.
None