12

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

joaquin
  • 82,968
  • 29
  • 138
  • 152
zjm1126
  • 63,397
  • 81
  • 173
  • 221

4 Answers4

17

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.

Matti Virkkunen
  • 63,558
  • 9
  • 127
  • 159
  • 1
    In Python3, this is now a function. You may need to pass in a fake locals/globals dictionary, perform the assignment to a known magic value, and do `fun = myFakeLocals['magic_value']` – ninjagecko May 07 '11 at 09:36
  • 1
    @ninjagecko: His code was using Python 2 syntax so I assumed he'd like his response in the same dialect. It's trivial to "port" to Python 3 though, just add parenthesis. No need to pass in locals/globals either. – Matti Virkkunen May 07 '11 at 09:38
  • oops, indeed you are quite correct; I was confusing it with an alternative method to `locals()[functionName]`, if you didn't know the name `fun` ahead of time – ninjagecko May 07 '11 at 09:43
  • [`eval`](https://docs.python.org/2/library/functions.html#eval) 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`](https://docs.python.org/2/library/functions.html#compile), you can `eval` arbitrary code, e.g. `eval(compile(mystr, '', 'exec'))` works fine (and works identically on Python 2 and Python 3, unlike `exec`). – ShadowRanger Feb 26 '16 at 21:08
  • "But before you do that, think about whether you really need dynamic code or not. By far most things can be done without.", Yes, otherwise I would be writing VBScript. "By far most things can be done without.", and would be better done with by being more parallelizable(if C had built in function-to-shellcode precompiler, threads would be much more practical to write without resorting to a higher language or making a global function for every thread proc) and not cluttering global scope with stuff only used once. – Dmytro Oct 25 '16 at 00:15
3

Eval evalutes only expressions, while exec executes statements.

So you try something like this

a = \
'''def fun():\n
    print 'bbb'
'''
exec a

fun()
Abdul Kader
  • 5,781
  • 4
  • 22
  • 40
2

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).

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • 1
    Doing this in python 3.7 returns `None` and not the function object. – Jonno_FTW Sep 13 '19 at 07:11
  • @Jonno_FTW: It's not supposed to return it (`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 `dict`s 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. – ShadowRanger Sep 13 '19 at 10:38
1

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.

zashu
  • 747
  • 1
  • 7
  • 22