How to define function from string using python

this is my code:

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

but it shows an 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

+6
source share
4 answers

eval() with string The string argument is for expressions only. If you want to execute instructions, use exec :

 exec """def fun(): print 'bbb' """ 

But before you do this, think about whether you really need dynamic code or not. In fact, much can be done without.

+11
source

Eval evaluates only expressions, and exec executes instructions.

So you will try something like this

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

Without an eval expression, the arguments must be compile -ed first; a str processed only as an expression, so compile is required for complete statements and arbitrary code.

If you mix it with compile , you can eval to execute arbitrary code, for example:

 eval(compile('''def fun(): print 'bbb' ''', '<string>', 'exec')) 

This works fine and works the same on Python 2 and Python 3, unlike exec (which is a keyword in Py2 and a function in Py3).

+2
source

If your logic is very simple (i.e. one line), you can define a lambda expression:

 a = eval("lambda x: print('hello {0}'.format(x))") a("world") # prints "hello world" 

As already mentioned, it is probably best to avoid eval if you can.

0
source

Source: https://habr.com/ru/post/887507/


All Articles