this is my code :
a = \
'''def fun():\n
print 'bbb'
'''
eval(a)
fun()
but it shows error :
Traceback (most recent call last):
File "c.py", line 8, in <module>
eval(a)
File "<string>", line 1
def fun():
^
SyntaxError: invalid syntax
so what can i do ,
thanks
-
Why do you need eval() ?user2665694– user26656942011年05月07日 09:12:29 +00:00Commented May 7, 2011 at 9:12
4 Answers 4
eval() with a string argument is only for expressions. If you want to execute statements, use exec:
exec """def fun():
print 'bbb'
"""
But before you do that, think about whether you really need dynamic code or not. By far most things can be done without.
5 Comments
fun = myFakeLocals['magic_value']locals()[functionName], if you didn't know the name fun ahead of timeeval is not solely for expressions; it's just that str arguments must be expressions, but it can also take code objects of arbitrary complexity. If you mix it with compile, you can eval arbitrary code, e.g. eval(compile(mystr, '<string>', 'exec')) works fine (and works identically on Python 2 and Python 3, unlike exec).Eval evalutes only expressions, while exec executes statements.
So you try something like this
a = \
'''def fun():\n
print 'bbb'
'''
exec a
fun()
Comments
Non-expression eval arguments must be compile-ed first; a str is only processed as an expression, so full statements and arbitrary code require compile.
If you mix it with compile, you can eval arbitrary code, e.g.:
eval(compile('''def fun():
print('bbb')
''', '<string>', 'exec'))
The above works fine and works identically on Python 2 and Python 3, unlike exec (which is a keyword in Py2, and a function in Py3).
2 Comments
None and not the function object.def is not an expression, it doesn't produce anything assignable), it just adds it to the current scope (local if within a function, global otherwise, and you can optionally pass alternate dicts for globals or locals). eval is only expected to produce a useful return value when used with strings or with compile in 'eval' mode; in 'single' or 'exec' mode, it's not evaluating expressions.If your logic is very simple (i.e., one line), you could eval a lambda expression:
a = eval("lambda x: print('hello {0}'.format(x))")
a("world") # prints "hello world"
As others have mentioned, it is probably best to avoid eval if you can.