In Python, eval() is a built-in function that executes a string as a Python expression and returns the result of the expression.

eval() Function Syntax

eval(expression, globals=None, locals=None)

Parameters:

  • expression: The Python expression to execute.
  • globals and locals: Optional parameters for specifying global and local namespaces. If omitted, eval() executes the expression in the current scope.

The eval() function returns the result of executing the expression.

eval() can only execute single expressions, not multiple statements or code containing control flow. To execute multiple statements, use the exec() function.

eval() Function Examples

Here's an example using the eval() function:

x = 1
y = 2
expression = "x + y"

result = eval(expression)
print(result)

The eval() function can execute any valid Python expression, including function calls and object attribute access.

If the expression contains undefined variables, functions, or syntax errors, it will raise an exception.

Security Considerations

The eval() function's parameter is a string, so use it cautiously. If the string comes from an untrusted source, it may cause security issues:

## Dangerous code!
eval('__import__("os").system("rm -rf /examples")')

You can use namespaces to restrict function usage:

x = 5  # Global variable

safe_namespace = {
    'a': 1,
    'b': 2,
    '__builtins__': {
        'sum': sum,
        'abs': abs
    }
}

# Using namespace, only allows sum and abs functions and variables a, b
result = eval('sum([a, b])', safe_namespace)
# len function not in namespace, cannot be used
result = eval('len([a, b])', safe_namespace)
# Cannot access global variable x
result = eval('sum([a, b, x])', safe_namespace)