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
2010-04-13 02:27:22
Running inside a dictionary made it work. Thans
None
2010-04-13 03:45:46
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
2010-04-13 02:30:18
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
2010-04-13 02:34:23
`eval()` in Python only accepts expressions, and assignment is a statement, not an expression.
Greg Hewgill
2010-04-13 02:34:43
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
2010-04-13 04:35:01
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
2010-04-13 03:42:38