Evaluate a configurable expression
A trusted, internally generated expression must be computed against a controlled set of names.
Python · Function
eval() evaluates a Python expression from source text or a code object and returns its result. Optional global and local namespaces control name resolution.
eval() parses source as a Python expression and evaluates it using optional global and local namespaces. If omitted, those namespaces come from the calling environment; the result of the expression is returned.
eval(source, /, globals=None, locals=None)| Name | Type | Description |
|---|---|---|
expression | str | code object | A Python expression as a string or code object. |
globals | dict | None | The global namespace; when supplied, it must be a dictionary. |
locals | mapping | None | The local namespace; it can be any mapping object. |
The result of the evaluated expression.
expression = "price * quantity"
context = {"price": 12, "quantity": 3}
result = eval(expression, {"__builtins__": {}}, context)
print(result) # 36Evaluates a trusted arithmetic expression with explicitly supplied names and no built-in names.
A trusted, internally generated expression must be computed against a controlled set of names.
A previously compiled expression needs to be run repeatedly.
eval() accepts a string or code object representing a Python expression and returns that expression's result. It is not a general statement executor.
Follow-up: How can its available names be controlled? Pass explicit globals and locals mappings, typically restricting globals such as __builtins__.
If globals and locals are omitted, eval() uses the environment at the call site. If only globals is supplied, locals defaults to that same dictionary.
Follow-up: What type must globals have? It must be a dictionary; locals can be any mapping object.
A globals dictionary that lacks __builtins__ receives a reference to the built-in module dictionary before parsing. This means merely passing an otherwise small globals dictionary does not automatically remove built-ins.
Follow-up: What is the security implication? Untrusted source must not be evaluated; use a purpose-built parser or safer data format instead.
compile()exec()__builtins__