Built-in Functions and Types

eval()

Evaluate a Python expression or an appropriate compiled code object. The result is the expression value; evaluating a code object compiled in exec mode returns None. Explicit namespaces control name lookup, but are not a security sandbox. Never evaluate text supplied by users or external services. Use ordinary expressions, explicit dispatch or a data parser such as json.loads for data instead. SyntaxError, NameError and exceptions from evaluated operations can propagate.

Formal Syntax & Structure

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

Parameters & Attributes

NameTypeDescription
sourcestr | code objectTrusted Python expression or compiled code object; positional only.
globalsdict | NoneGlobal namespace; defaults to caller globals.
localsmapping | NoneLocal namespace; defaults to globals when globals alone is supplied, otherwise caller-local behavior.

Return Value

object

Expression result, or None for an exec-mode code object.

Working Example

Example Snippetpython
# Fixed trusted source, not a calculator for user input.values = {"width": 7, "height": 4}print(eval("width * height", globals=values))print(7 * 4)  # Ordinary expression preferred for this task.
Python Reference