How can I assign the value of a variable using eval in python?

后端 未结 4 1217
感动是毒
感动是毒 2020-11-27 16:17

Okay. So my question is simple: How can I assign the value of a variable using eval in Python? I tried eval(\'x = 1\') but that won\'t work. It returns a Syntax

4条回答
  •  囚心锁ツ
    2020-11-27 17:11

    Because x=1 is a statement, not an expression. Use exec to run statements.

    >>> exec('x=1')
    >>> x
    1
    

    By the way, there are many ways to avoid using exec/eval if all you need is a dynamic name to assign, e.g. you could use a dictionary, the setattr function, or the locals() dictionary:

    >>> locals()['y'] = 1
    >>> y
    1
    

    Update: Although the code above works in the REPL, it won't work inside a function. See Modifying locals in Python for some alternatives if exec is out of question.

提交回复
热议问题