Python Reference ยท Built-in Functions
Python eval() function
Reference for Python eval(): evaluate an expression string, pass globals and locals, why it is unsafe on untrusted input, and ast.literal_eval as the safer choice.
eval() takes a string containing a single Python expression, compiles it, runs it and returns the value. eval("2 + 3 * 4") gives 14. It also accepts a code object produced by compile() in "eval" mode.
eval() runs arbitrary code with your program's permissions. It must never be used on text that comes from users, files, the network or any source you do not fully control. For turning text such as "[1, 2, {'a': 3}]" into a Python value, use ast.literal_eval(), and for data exchange use json.
print(eval("2 + 3 * 4")) # 14
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
eval(expression, globals=None, locals=None)
| Name | Description |
|---|---|
expression |
A string with one Python expression, or a code object from compile(..., mode="eval"). Leading and trailing spaces and tabs are ignored. |
globals |
Optional dictionary used as the global namespace. If omitted, the caller's globals are used. |
locals |
Optional mapping used as the local namespace. If omitted, it defaults to globals when that is given, otherwise the caller's locals. |
Return value: the value of the expression.
Raises: SyntaxError for invalid or non-expression text; any exception the expression itself raises.
Usage notes
- Security first. Evaluating
"__import__('os').system(...)"runs commands on your machine. Removing builtins with{"__builtins__": {}}does not makeevalsafe: attribute tricks on ordinary objects can still escape. Treat anyevalof untrusted input as a vulnerability. - Use
ast.literal_eval()for literals only: strings, numbers, tuples, lists, dicts, sets, booleans andNone. It refuses calls and operators beyond simple negative numbers and complex literals. - Expressions only. Assignments,
import,defand loops are statements and needexec(). __builtins__is injected. Ifglobalshas no"__builtins__"key, Python adds a reference to the real builtins, which is whyeval("len('ab')", {})still works.- Mutation. The
globalsdictionary may gain a__builtins__entry. Passing your own dictionary avoids touching the caller's globals. - Speed. Parsing the string happens on every call. For repeated use,
compile()once andeval()the code object. - Better alternatives. Dispatch tables,
getattr(),operator,json.loads()and real parsers almost always replaceeval.