how to define a function from a string using python

后端 未结 4 1018
时光说笑
时光说笑 2020-12-06 17:45

this is my code :

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

fun()

but it shows error :

Traceback (most r         


        
相关标签:
4条回答
  • 2020-12-06 18:28

    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.

    0 讨论(0)
  • 2020-12-06 18:28

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

    0 讨论(0)
  • 2020-12-06 18:37

    Eval evalutes only expressions, while exec executes statements.

    So you try something like this

    a = \
    '''def fun():\n
        print 'bbb'
    '''
    exec a
    
    fun()
    
    0 讨论(0)
  • 2020-12-06 18:46

    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.

    0 讨论(0)
提交回复
热议问题