Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to define a function from a string using python

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

like image 703
zjm1126 Avatar asked May 07 '11 09:05

zjm1126


2 Answers

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.

like image 88
Matti Virkkunen Avatar answered Sep 28 '22 05:09

Matti Virkkunen


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.

like image 39
zashu Avatar answered Sep 28 '22 07:09

zashu