Python Glossary Русский

all Python 3Built-in functionsterm

eval

execution

Evaluates an expression given as a string. WARNING: unsafe for untrusted input!

Syntax

eval(expression[, globals[, locals]])

eval evaluates exactly one expression and returns its value — assignments, if statements and loops will not go through it; those need exec. Handing it a stripped-down globals dict is not a sandbox: builtins and __import__ remain reachable from almost any expression, so the only real defence is never feeding eval a string you did not write. To turn user input into a number or a literal, use int(), float() or ast.literal_eval(), which understands constants only and executes nothing.

Examples

print(eval('2**10'))  # → 1024
print(eval('[x**2 for x in range(5)]'))  # → [0,1,4,9,16]
x = 10
print(eval('x + 5'))  # → 15
print(eval('1+2', {}))  # → 3 (пустой globals)
print(eval('abs(-5)', {'abs':abs}))  # → 5

See also

Open in the full glossarydocs.python.orgReport an inaccuracy