Python’s eval()
function runs Python code stored as a string. It takes a string, treats it as a Python expression, and then calculates its value. This lets you run code that is not directly written in your program.
It helps you execute dynamic code. You can use it to evaluate mathematical expressions or even call functions from strings. This helps when you need to run user-provided input as code.
What is eval()
?
A Python eval()
function runs a string as a Python expression and returns the result. You provide a string, and eval()
processes it as if it were a piece of live Python code.
It takes three arguments:
- expression: This is the string you want to evaluate. It must be a valid Python expression.
- globals (optional): This is a dictionary. It specifies the global namespace that
eval()
will use. - locals (optional): This is another dictionary. It specifies the local namespace that
eval()
will use.
You can use eval()
for simple calculations or more complex tasks.
In this course, you will learn the fundamentals of Python: from basic syntax to mastering data structures, loops, and functions. You will also explore OOP concepts and objects to build robust programs.
3 Ways to Use eval()
in Python
You can use eval()
for various tasks:
- Evaluate Math Expressions: Run calculations from strings.
- Run Dynamic Code: Execute simple Python statements from strings.
- Work with Scope: Control which variables
eval()
can see.
Let’s look at each one.
1. Evaluate Math Expressions
The most common use of eval()
is to calculate mathematical expressions. You give it a string containing numbers and operators, and it returns the answer.
Here is an example:
# Evaluate a simple math expression
result = eval("10 + 5")
print(result)
# Evaluate a more complex expression
result_complex = eval("2 * (3 + 4) / 7")
print(result_complex)
This code outputs:
15
2.0
You pass the math expressions as strings. eval()
handles the calculation. This is useful for building calculators or processing formulas from text.
You can also evaluate expressions that include variables, if those variables are defined in the current scope:
x = 10
y = 20
# Evaluate an expression with variables
result_vars = eval("x * y + 5")
print(result_vars)
This code outputs:
205
The eval()
function sees x
and y
from the surrounding code and uses their values.
2. Run Dynamic Code
You can use eval()
to run more than just math. It can execute any valid Python expression, including function calls or data structure creations.
Here is an example that creates a list from a string:
# Create a list from a string
list_str = "[1, 2, 3, 4, 5]"
my_list = eval(list_str)
print(my_list)
print(type(my_list))
This code outputs:
[1, 2, 3, 4, 5]
<class 'list'>
eval()
takes the string representation of a list and turns it into an actual Python list. This is useful for converting string data into Python objects.
You can also call functions defined in your code:
def greet(name):
return "Hello, " + name + "!"
# Call a function using eval()
message = eval("greet('Alice')")
print(message)
This code outputs:
Hello, Alice!
eval()
runs the greet()
function using the string. This shows its power in running dynamic code based on strings.
3. Work with Scope (globals
and locals
)
The eval()
function lets you control the environment in which the expression runs. You can use the optional globals
and locals
dictionaries to define which variables and functions eval()
can access.
- globals: This dictionary provides the global variables for the evaluation.
- locals: This dictionary provides the local variables for the evaluation.
If you do not provide globals
and locals
, eval()
uses the current environment.
Here is an example using globals
to restrict access:
# Define some variables
global_var = 100
local_var = 200
# Create a restricted global dictionary
# Only 'global_var' is available to eval()
restricted_globals = {'global_var': global_var}
try:
# This works because 'global_var' is in restricted_globals
result1 = eval("global_var + 50", restricted_globals)
print(f"Result with restricted globals: {result1}")
# This will raise an error because 'local_var' is not in restricted_globals
result2 = eval("local_var + 50", restricted_globals)
print(f"Result with restricted globals (error expected): {result2}")
except NameError as e:
print(f"Error when accessing unauthorized variable: {e}")
This code outputs:
Result with restricted globals: 150
Error when accessing unauthorized variable: name 'local_var' is not defined
By providing restricted_globals
, you control what eval()
can see. This helps with security.
You can also use locals
to provide specific variables:
# Define local variables for eval()
exec_locals = {'a': 10, 'b': 20}
# Evaluate using specific local variables
result = eval("a * b", {}, exec_locals) # {} means no special globals
print(result)
This code outputs:
200
This shows how you can isolate the eval()
execution environment. This is important for managing dynamic code safely.
Risks of eval()
While eval()
is powerful, it carries risks. Never use eval()
with untrusted input.
If you let a user provide the string for eval()
, they could type malicious code. This code could:
- Delete files from your system.
- Access sensitive information.
- Run other harmful commands.
Consider this example:
# RISKY: Do NOT use with untrusted input!
user_input = "__import__('os').system('rm -rf /')" # Example: delete all files
try:
eval(user_input)
print("Code executed.")
except Exception as e:
print(f"An error occurred: {e}")
This example shows a harmful string. If executed, it would try to delete all files on your system. Always treat user input to eval()
as a major security risk.
Use eval()
only when you fully control the input string.
For simple mathematical expressions, ast.literal_eval()
is a safer alternative. It only evaluates literal structures (strings, numbers, tuples, lists, dicts, booleans, None), preventing arbitrary code execution.