pythoneval

What does Python's eval() do?


The book that I am reading on Python repeatedly shows code like eval(input('blah')).

How exactly does this modify the result from calling input?


See also: Why is using 'eval' a bad practice? to understand the critical security risks created by using eval or exec on untrusted input (i.e.: anything that is even partially under the user's control, rather than the program's control).

See also: How can I sandbox Python in pure Python?. The short version is that doing this properly will always be harder than choosing a proper tool instead of eval or exec.

See Using python's eval() vs. ast.literal_eval() for a potentially safer technique.

See How do I use raw_input in Python 3? for background context on why a book might have contained code like this, or why OP might originally have expected an input result not to require further processing.


Solution

  • The eval function lets a Python program run Python code within itself.

    eval example (interactive shell):

    >>> x = 1
    >>> eval('x + 1')
    2
    >>> eval('x')
    1