Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

eval()

Evaluates a Python expression in the supplied namespace and returns its value.

Version: Python 3.14; repository image, production runtime not attested

Syntax

eval(source, /, globals=None, locals=None)

Evaluates a Python expression in the supplied namespace and returns its value.

An ordinary assignment statement using = cannot be parsed in expression mode. Use this facility only with trusted source.

For source text, eval parses one expression and returns its value. The supplied namespace binds a to 4, so a*3 yields 12. Ordinary assignment is a statement and raises SyntaxError in expression text. A precompiled code object is also accepted; one compiled in exec mode executes and returns None. Python inserts the built-ins dictionary under __builtins__ when the supplied globals dictionary lacks that key. Only evaluate trusted source.

scope = {"a": 4}
assert eval("a * 3", scope) == 12
assert isinstance(scope["__builtins__"], dict)
assert eval(compile("a = 9", "<eval>", "exec"), scope) is None and scope["a"] == 9

Examples

print(eval("a * 3", {"a": 4}))
try:
    eval("a = 12")
except SyntaxError as error:
    print(type(error).__name__)

Result

12
SyntaxError

For source text, eval parses one expression and returns its value. The supplied namespace binds a to 4, so a*3 yields 12. Ordinary assignment is a statement and raises SyntaxError in expression text. A precompiled code object is also accepted; one compiled in exec mode executes and returns None. Python inserts the built-ins dictionary under `__builtins__` when the supplied globals dictionary lacks that key. Only evaluate trusted source.

Sources